有没有办法动态创建React组件

时间:2019-07-03 20:04:40

标签: reactjs

我在React应用程序中有多个地方,上面有如下代码,只是一个很大的开关,其格式会加载相应的组件。有没有办法在React中动态创建组件?类似于Java中的反射,我可以在其中做Class.instanceOf(“ Rule” + this.props.selectedFormatId“);

renderRules() {
   switch (this.props.selectedFormatId) {
     case 1:
       return <Rules1 intl={this.props.intl} onRuleChange={this.props.onRuleChange}/>
     case 6:
       return <Rules6 intl={this.props.intl} onRuleChange={this.props.onRuleChange}/>
     case 7:
       return <Rules7 intl={this.props.intl} onRuleChange={this.props.onRuleChange}/>
       }
}

最终的目标是继续向软件添加新规则,而不必进入这些开关出现和更新的5个位置。

2 个答案:

答案 0 :(得分:2)

是的,这是绝对可能的。您可以执行以下操作:

const dynamicComponents = {
  1: Rules1,
  2: Rules2,
  3: Rules3
}
const someValue = 1
const DynamicComponent = dynamicComponents[someValue]
return <DynamicComponent intl={this.props.intl} onRuleChange={this.props.onRuleChange} /> // This would be Rules1

这将呈现Rule1。这意味着要添加一个新组件,您只需要将其添加到dynamicComponents对象。如果您想使其更简单,则可以使用一个数组:

const dynamicComponents = [
  Rules1,
  Rules2,
  Rules3
]
const someValue = 2
const DynamicComponent = dynamicComponents[someValue]
return <DynamicComponent intl={this.props.intl} onRuleChange={this.props.onRuleChange} /> // this would be Rules2

答案 1 :(得分:1)

我解决类似问题的方法是在键和组件构造函数之间保存一个对象文字(“映射”),然后在给定键的情况下,我对Component有了引用。

const compMap = {
  key1: require('./Component1'),
  key2: require('./Component2'),
  key3: require('./Component3'),
};

// usage of the map
renderRules() {
  const Comp = compMap[this.props.selectedFormatId];
  return (<Comp prop1="prop1" />);
}

相关问题