自动将相同的道具映射到多个React组件

时间:2017-09-25 19:49:34

标签: reactjs

我有多个React组件会收到相同的道具......

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

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

上面的代码工作正常但是有更动态的方法吗? Mabye对一组组件名称进行.map()

1 个答案:

答案 0 :(得分: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>