2015-05-14 161 views
0

我無法找到此解決方案。我如何將下面的代碼轉換爲更加動態和簡潔的內容?動態生成React組件名稱

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 

回答

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}) 
    } 
}); 
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>; 
    } 
}); 
+0

感謝@Crob,這不會出現雖然要爲我工作。有什麼想法嗎?我註銷了'component' var,它似乎在抓取組件,但它並沒有實例化組件 – Ben