【问题标题】:Render Dynamically Created React Component渲染动态创建的 React 组件
【发布时间】:2020-07-12 18:31:57
【问题描述】:

我正在尝试将几个 SVG 图标动态渲染为 React 组件,下面是 Icon 文件的示例。

module.exports = {
    AR: React.createClass({
        render: function() {
            return (
                <svg xmlns="http://www.w3.org/2000/svg" width="20" height="11" viewBox="0 0 20 11">
                </svg>
            );
        }
    }),
    AU: React.createClass({
        render: function() {
            return (
                <svg xmlns="http://www.w3.org/2000/svg" width="20" height="11" viewBox="0 0 20 11">
                </svg>
            );
        }
    }),
    ----few other components
}

然后要求这个文件,

var Icons = require('./Icons');

然后尝试像这样根据 prop 值动态渲染组件,但它没有按预期渲染组件。

<i className="footer-img">{() => Icons[this.props.country.code]}</i>

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    你不需要箭头基金和React.createClass

    <i className="footer-img">{Icons[this.props.country.code]}</i>
    
     module.exports = {
        AR: <svg xmlns="http://www.w3.org/2000/svg" width="20" height="11" viewBox="0 0 20 11"></svg>,
        AU: <svg xmlns="http://www.w3.org/2000/svg" width="20" height="11" viewBox="0 0 20 11"></svg>,
        ----few other components
    }
    

    【讨论】:

      【解决方案2】:

      您可以将 svg 组件直接保存在您的图标对象键上,并像使用普通组件一样使用它,试试这个:

      module.exports = {
        AR: () => (
          <svg
            xmlns="http://www.w3.org/2000/svg"
            width="20"
            height="11"
            viewBox="0 0 20 11"
          ></svg>
        ),
        AU: () =>(
          <svg
            xmlns="http://www.w3.org/2000/svg"
            width="20"
            height="11"
            viewBox="0 0 20 11"
          ></svg>
        )
      };
      

      然后需要这个并使用它:

      var Icons = require('./Icons');
      
      const YourApp = ({ country }) => {
            const IconComponent = Icons[country.code];
      
            return (
              <i className="footer-img">
                {<IconComponent />}
              </i>
            );
          };
      

      【讨论】:

        猜你喜欢
        • 2014-12-18
        • 2020-02-28
        • 1970-01-01
        • 1970-01-01
        • 2022-01-25
        • 1970-01-01
        • 2015-02-10
        • 2018-02-17
        • 2018-12-21
        相关资源
        最近更新 更多