简体   繁体   English

将道具传递到不同组件的映射数组

[英]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.

相关问题 如何将props传递到从组件数组映射的组件? - How to pass props to a component mapped from an array of components? 将响应式道具传递给使用 object 键映射的延迟加载的 React 组件 - Pass reactive props to lazy loaded React components mapped with object key 如何将道具传递给带有样式组件的映射元素? - How to pass props to .mapped elements with styled-components? 如何在React Js中的路线映射数组上传递道具 - How to pass props on mapped array of routes in React Js 如何将道具传递给来自不同来源的组件? - How can I pass props to components from different sources? React + TS,当props略有不同并描述C props类型时,如何将组件A和B的props传递给组件C? - React + TS, how to pass props from components A & B to components C, when props are slightly different and describe C props type? 如何将 JSX 映射逻辑与包含带有 props 的组件的映射数组分开? - How can I separate the JSX mapping logic from the mapped array containing components with props? 将 props 发送到组件数组 - Send props to an array of components 如何 map 对象数组到 React 中的不同组件道具? - How to map an array of objects to different components props in React? 如何将道具传递给样式组件 - how to pass props to styled components
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM