React / JSX动态组件名称

我试图根据其类型动态呈现组件。


例如:


var type = "Example";

var ComponentName = type + "Component";

return <ComponentName />; 

// Returns <examplecomponent />  instead of <ExampleComponent />

我尝试了这里提出的解决方案React / JSX动态组件名称


这在编译时给了我一个错误(使用browserify for gulp)。它期望我使用数组语法的XML。


我可以通过为每个组件创建一个方法来解决这个问题:


newExampleComponent() {

    return <ExampleComponent />;

}


newComponent(type) {

    return this["new" + type + "Component"]();

}

但这对我创建的每个组件都意味着一种新方法。必须有一个更优雅的解决方案来解决这个问题。


我对建议很开放。


忽然笑
浏览 2398回答 3
3回答

慕桂英3389331

我想出了一个新的解决方案。请注意我使用的是ES6模块,所以我要求上课。您也可以定义一个新的React类。var components = {&nbsp; &nbsp; example: React.createFactory( require('./ExampleComponent') )};var type = "example";newComponent() {&nbsp; &nbsp; return components[type]({ attribute: "value" });}
打开App,查看更多内容
随时随地看视频慕课网APP