简体   繁体   English

如何动态地向对象添加反应图标

[英]How to dynamically add react icons to an Object

I'm building an accordion for this website and im having trouble adding react icons to the title of each accordion title.我正在为这个网站构建一个手风琴,但我无法在每个手风琴标题的标题中添加反应图标。 I've used this approach below to dynamically add accordion tabs with the contents being those 3 components that are in the content object.我在下面使用这种方法来动态添加手风琴选项卡,其内容是内容对象中的 3 个组件。

How would I even add a simple h2 tag to each accordion tab title dynamically我什至如何动态地为每个手风琴标签标题添加一个简单的 h2 标签

const content = {
  'Blogs': <Blogs />,
  'icon': <h2>hi</h2>,
  'Webinars': <Webinars />,
  'Podcast': <Podcasts />,
}

const AccordionSingle = (name) => {
  const [isOpen, setOpen] = useState(false);

  return (
    <div className="accordion-wrapper">
      <div
        className={`accordion-title ${isOpen ? "open" : ""}`}
        onClick={() => setOpen(!isOpen)}
      >
        {name}
      </div>
      <div className={`accordion-item ${!isOpen ? "collapsed" : ""}`}>
        <div className="accordion-content">{content[name]}</div>
      </div>
    </div>
  );
};

const Resources = (props) => {

  return (
    <>
      <Navbar />
      <div>
        {
          ['Webinars', 'Blogs', 'Podcast'].map(d => AccordionSingle(d))
        }
      </div>
    </>
  );
}

export default Resources;

if I got you correct, you want to add icons to all titles within your accordion (or any other text, h2 for example).如果我猜对了,您想为手风琴中的所有标题添加图标(或任何其他文本,例如 h2)。 From that point it is not clear why you are adding h2 to the items list.从那时起,不清楚为什么要将 h2 添加到项目列表中。 It should be added inside of your div containing title:它应该添加到包含标题的 div 中:

<div
  className={`accordion-title ${isOpen ? "open" : ""}`}
  onClick={() => setOpen(!isOpen)}
>
  <h2>text</h2>{name}
</div>

Also, I would recommend to store your items as an array because it is actually a list of items with own properties.此外,我建议将您的项目存储为一个数组,因为它实际上是一个具有自己属性的项目列表。 It may look like this:它可能看起来像这样:

const items = [
  { 
    name: "Blogs",
    content: <Blogs />,
    icon: <FaPenFancy /> // it is just an example from react-icons
  },
  ...
]

This way you can later use the icon as a part of title instead of shown above.这样您以后就可以将图标用作标题的一部分,而不是上面显示的。

This way it is better to update the code with sending the entire item object to AccordionSingle props:这样最好通过将整个项目对象发送到 AccordionSingle props 来更新代码:

// instead of:
{
  ['Webinars', 'Blogs', 'Podcast'].map(d => AccordionSingle(d))
}
// should be:
  items.map(d => AccordionSingle(d))

// and then extract all properties inside you AccordionSingle props:
const AccordionSingle = ({name, content, icon}) => {
  ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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