渲染动态创建的 React 组件

我正在尝试将几个 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>


慕尼黑的夜晚无繁华
浏览 378回答 2
2回答

慕沐林林

你不需要箭头基金和React.createClass<i className="footer-img">{Icons[this.props.country.code]}</i>&nbsp;module.exports = {&nbsp; &nbsp; AR: <svg xmlns="http://www.w3.org/2000/svg" width="20" height="11" viewBox="0 0 20 11"></svg>,&nbsp; &nbsp; AU: <svg xmlns="http://www.w3.org/2000/svg" width="20" height="11" viewBox="0 0 20 11"></svg>,&nbsp; &nbsp; ----few other components}

当年话下

您可以将 svg 组件直接保存在您的图标对象键上,并像使用普通组件一样使用它,试试这个:module.exports = {&nbsp; AR: () => (&nbsp; &nbsp; <svg&nbsp; &nbsp; &nbsp; xmlns="http://www.w3.org/2000/svg"&nbsp; &nbsp; &nbsp; width="20"&nbsp; &nbsp; &nbsp; height="11"&nbsp; &nbsp; &nbsp; viewBox="0 0 20 11"&nbsp; &nbsp; ></svg>&nbsp; ),&nbsp; AU: () =>(&nbsp; &nbsp; <svg&nbsp; &nbsp; &nbsp; xmlns="http://www.w3.org/2000/svg"&nbsp; &nbsp; &nbsp; width="20"&nbsp; &nbsp; &nbsp; height="11"&nbsp; &nbsp; &nbsp; viewBox="0 0 20 11"&nbsp; &nbsp; ></svg>&nbsp; )};然后要求它并使用它:var Icons = require('./Icons');const YourApp = ({ country }) => {&nbsp; &nbsp; &nbsp; const IconComponent = Icons[country.code];&nbsp; &nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; &nbsp; <i className="footer-img">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {<IconComponent />}&nbsp; &nbsp; &nbsp; &nbsp; </i>&nbsp; &nbsp; &nbsp; );&nbsp; &nbsp; };
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript