微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在 React 中使用变量渲染组件

如何解决在 React 中使用变量渲染组件

我在“卡片组件”中有一个通过道具传递的 react-icons 列表。在我的 Card 组件的渲染方法中,我有这样的东西:

render() {
  ...
  {
     this.props.icons.map(icon => {
        return (
          <div className="icon-square">
            /*   What should I do here so I render the "icon" variable"   */
          </div>
        )
     })
   }
}

注意:该列表由 React 组件本身的 react-icons 组成。

我尝试了很多东西,但我不太明白如何渲染图标。如果有人可以帮助我,那就太棒了。谢谢

解决方法

如果图标是一个 react 组件,则:

this.props.icons.map(Icon => {
        return (
          <div className="icon-square">
            <Icon/>
          </div>
        )
     })
,

假设你已经传递了一个图标列表

import { FaBeer,FaBug,FaAnchor,FaCoffee } from 'react-icons/fa';

const icons = [FaBeer,FaCoffee];

ReactDOM.render(
    <CardComponent icons = {icons} />,document.querySelector('root')
};

CardComponent.js

class CardComponent extends React.Component{
...

render() {

  // Icon is a Component
  return (
    this.props.icons.map((Icon) => {
     return <Icon />
    });
  )

 }
}
,

使用你的图标有两个不同之处,如果你作为 JSX 传递,你应该使用 {icon} 但是如果你作为一个组件传递,你应该像这样使用 <Icon/>

,

我认为包装你只需要放置图标是 {}

render() {
  ...
  {
     this.props.icons.map(icon => {
        return (
          <div className="icon-square">
            {icon}
          </div>
        )
     })
   }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。