我有一系列导入的具有不同名称的React组件,我想迭代它们并将相同的道具传递给每个组件,但我无法找到正确的方法
这是我的伪代码形式:
const myArray = [
<Component1 />,
<Component2 />,
<Component3 />,
];
render() {
return(
<div>
{myArray.map( ComponentX => {ComponentX} )} // pass the same props into these components?
</div>
);
}
答案 0 :(得分:3)
不要在数组中使用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'));
&#13;
<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>
&#13;
答案 1 :(得分:0)
您可以使用React.cloneElement()
:
render() {
const myArray = [
<Component1 />,
<Component2 />,
<Component3 />,
];
const extraProps = {
foo: 'bar'
};
return (
<div>
{myArray.map(comp => React.cloneElement(comp, extraProps))}
</div>
);
}