[英]Pass props to a mapped array of different components
I have an array of imported React components with different names, and I'd like to iterate over them and pass the same props to each of them, but I can't find a way to do this properly. 我有一系列导入的具有不同名称的React组件,我想遍历它们并将相同的prop传递给每个组件,但是我找不到合适的方法。
Here's what I have in a form of pseudocode: 这是伪代码形式的内容:
const myArray = [
<Component1 />,
<Component2 />,
<Component3 />,
];
render() {
return(
<div>
{myArray.map( ComponentX => {ComponentX} )} // pass the same props into these components?
</div>
);
}
Don't use JSX inside the array and you should be good: 不要在数组内部使用JSX,这应该很好:
class Component1 extends React.Component { render() { return <div>{this.props.prop}</div>; } } class Component2 extends React.Component { render() { return <div>{this.props.prop}</div>; } } const myArray = [ Component1, Component2, ]; class App extends React.Component { render() { return ( <div> {myArray.map(ComponentX => <ComponentX prop="Hello World!" /> )} </div> ); } } ReactDOM.render(<App/>, document.getElementById('View'));
<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="View"></div>
You can do that with React.cloneElement()
: 您可以使用
React.cloneElement()
做到这React.cloneElement()
:
render() {
const myArray = [
<Component1 />,
<Component2 />,
<Component3 />,
];
const extraProps = {
foo: 'bar'
};
return (
<div>
{myArray.map(comp => React.cloneElement(comp, extraProps))}
</div>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.