在 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>
        )
     })
   }
}