动态确定要在运行时呈现的Component

时间:2017-03-19 16:25:03

标签: reactjs

我在ReactComponent类中有以下代码:

render() {
    const snippets = entity.snippets.map(
        function (snippet, props) {
            const SnippetType = snippet['type'];
            //const SnippetType = "Text";
            return <SnippetType key={Math.random()} />;
        }
    );
// .......
    return (
        <article>
            {snippets};
        </article>
    )
}

Text Component看起来像这样。

const Text = (props) => (
    <div className="snippet text-snippet">
        <h2>{props.name}</h2>
        <p>{props.content}</p>
    </div>
);

我不确定,我在这里做错了什么,但是<SnippetName ...>总是呈现HTML而不是实际的Component,即使我手动将Text定义为字符串(根据上面的评论说明。)

经过几个小时的失败后,我问你:我做错了什么?

1 个答案:

答案 0 :(得分:0)

您在snippet变量中存储了什么?如果存储加载组件的结果(即const snippet['type'] = require('MyTextComponent')),那么这应该有效。

将字符串呈现为组件并不起作用,因为字符串不是组件。比较将变量设置为组件与字符串时变量的样子,并且您将看到我的意思(即对于您的注释//const SnippetType = "Text";

也许尝试像

这样的东西
const SnippetComponents = {};
SnippetComponents['text'] = require('MyTextComponent');

然后你可以去

const Snippet = SnippetComponents['text']
<Snippet someProps={stuff}/>