2017-09-25 56 views
0

我有多個陣營,將接收到相同的道具部件...自動映射相同的道具多個反應的組分

... 
render() { 
    const { someProps } = this.props 

    return (
    <div className="someDiv"> 
     <Component1 someProps={someProps}/> 
     <Component2 someProps={someProps}/> 
    </div> 
) 
} 
... 

上面的代碼工作正常,但有沒有這樣做的一個更加動態的方式嗎? Mabye在Component名稱數組上做一個.map()

回答

0

組件的數組應該工作得很好。

const Component1 = (props) => <div>Component 1</div> 
 
const Component2 = (props) => <div>Component 2</div> 
 
const Component3 = (props) => <div>Component 3</div> 
 

 
const components = [Component1, Component2, Component3] 
 

 
class App extends React.Component { 
 
    render() { 
 
    const { someProps } = this.props 
 
    
 
    return (
 
     <div> 
 
     <h3>Root component</h3> 
 
     {components.map((Component, index) => 
 
      <Component key={index} someProps={someProps} /> 
 
     )} 
 
     </div> 
 
    ) 
 
    } 
 
} 
 

 
ReactDOM.render(
 
    <App />, 
 
    document.getElementById('root') 
 
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> 
 

 
<div id="root"></div>

+0

完美...謝謝!!!!得多 – kaidez

相關問題