简体   繁体   中英

React dynamically set custom tags

Rather than having to create a component per custom header type, I would like to do so dynamically.

const HEADERS = {
   'header-one': 'h1',
   'header-two': 'h2',
   'header-three': 'h3',
   'header-four': 'h4',
   'header-five': 'h5',
};

_

let tag = HEADERS[type] || 'span';
return (
  <{tag} id={id}>
      {props.children}
  </{tag}>
);

Ok after reading this: Dynamic tag name in jsx and React

I was able to figure it out that it needs to be a capital (NFI why?)

const Tag = HEADERS[type] || 'span';
return (
    <Tag id={id}>
        {props.children}
    </Tag>
);

Is now working. Still open to better answers or an explanation as too why it needs to be capital..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM