为了账号安全,请及时绑定邮箱和手机立即绑定

React / JSX动态组件名称

React / JSX动态组件名称

忽然笑 2019-08-31 16:24:24
我试图根据其类型动态呈现组件。例如: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"]();}但这对我创建的每个组件都意味着一种新方法。必须有一个更优雅的解决方案来解决这个问题。我对建议很开放。
查看完整描述

3 回答

?
慕桂英3389331

TA贡献2036条经验 获得超8个赞

我想出了一个新的解决方案。请注意我使用的是ES6模块,所以我要求上课。您也可以定义一个新的React类。


var components = {

    example: React.createFactory( require('./ExampleComponent') )

};


var type = "example";


newComponent() {

    return components[type]({ attribute: "value" });

}


查看完整回答
反对 回复 2019-08-31
  • 3 回答
  • 0 关注
  • 2405 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信