How to pass props to {this.props.children}

后端 未结 26 3849
猫巷女王i
猫巷女王i 2020-11-21 23:42

I\'m trying to find the proper way to define some components which could be used in a generic way:


  
  

        
26条回答
  •  孤城傲影
    2020-11-22 00:11

    When using functional components, you will often get the TypeError: Cannot add property myNewProp, object is not extensible error when trying to set new properties on props.children. There is a work around to this by cloning the props and then cloning the child itself with the new props.

    const MyParentComponent = (props) => {
      return (
        
    {props.children.map((child) => { const newProps = { ...child.props } // set new props here on newProps newProps.myNewProp = 'something' const preparedChild = { ...child, props: newProps } return preparedChild })}
    ) }

提交回复
热议问题