动态生成React组件名称

时间:2015-05-14 20:04:33

标签: coffeescript reactjs

我无法找到解决方法。如何将下面的代码转换为更动态,更简洁的内容?

OneComponent = require ('./OneComponent')
TwoComponent = require ('./TwoComponent')
ThreeComponent = require ('./ThreeComponent')

Example = React.createClass

  render: -> 
    filter = @props.filterState

    if filter is 'something'
      tableCmpt = 
        <div>
          <OneComponent
            tasks={@props.tasks}
          />
        </div>

    if filter is 'somethingElse'
      tableCmpt = 
        <div>
          <TwoComponent
            tasks={@props.tasks}
          />
        </div>

    ##... etc

    return tableCmpt

2 个答案:

答案 0 :(得分:5)

我做过这样的事情。

var Components = {
  'something': require('./Component'),
  'somethingElese': require('./Component2')
};

Example = React.createClass({
    render: function() {
      var component = Components[this.props.filter];
      return <div><component tasks={this.props.tasks}/></div>;
    }
});

答案 1 :(得分:0)

我无法得到Crob的工作答案(虽然我很欣赏哈希表的想法),但它让我找到了一个解决方案 - 我只是跳过了jsx步骤并使用了编译的js:

React.createElement(component, {tasks: this.props.tasks} )
总而言之:

var Components = {
  'something': require('./Component'),
  'somethingElese': require('./Component2')
};

Example = React.createClass({
    render: function() {
      var component = Components[this.props.filter];
      React.createElement(component, {tasks: this.props.tasks} )
    }
});