简体   繁体   English

将 props 发送到组件数组

[英]Send props to an array of components

I have an array of components that I want to render, but I don't know how to send props to each of them.我有一组要渲染的组件,但我不知道如何将 props 发送到每个组件。 Do you have any idea how?你知道怎么做吗? I am using also using formik for form management and the page components consist of basic inputs.我还使用 formik 进行表单管理,页面组件由基本输入组成。

const pages = [<Page1 />, <Page2 />, <Page3 />, <Page4 />]

and I am rendering them this way:我是这样渲染它们的:

<div>{pages[state]}</div>

You can accomplish this by using React.cloneElement :您可以通过使用React.cloneElement来完成此React.cloneElement

const newProps = {}

<div>{React.cloneElement(pages[state], newProps)}</div>

React.cloneElement React.cloneElement

There are 2 options to achieve this:有两种选择可以实现这一点:

Option 1: On the declaration site you may pass the state while initialising the array.选项 1:在声明站点上,您可以在初始化数组时传递状态

const pages = [<Page1 props={page1Prop: 'value'}/>, 
               <Page2 props=page2Props />, 
               <Page3 props=page3Props />, 
               <Page4 props=page4Props />]

Or if you do not want or can not update the declaration you may pass when rendering: Or you can或者,如果您不想或无法更新渲染时可能传递的声明:或者您可以

Option 2: clone the component prop and apply the new props选项 2:克隆组件 prop 并应用新的 props

  ...
  render() {
    return (
      <div>
        {React.cloneElement(pages[currentPage] propsForPage[currentPage])}
        OR
        {React.cloneElement(pages[currentPage] {someProp:'value'})}
      </div>
  );
 }
}

Could you not initialise the component in the array?你不能初始化数组中的组件吗?

const pages = [Page1, Page2, Page3, Page4]

return (
  <div>
    {pages.map(page => {
      const Component = <page />

      return (
        <Component {...props} />
      )
     }
  </div>
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM