How to safely inject props into React children?

社会主义新天地 提交于 2020-08-05 11:08:56

问题


I am building a React component which delays the unmounting of its children in order to animate them. When unmounting, I would like to pass in an additional prop (for example, a data-attribute or a class name) in order to handle animations.

This is a specific instance of a general situation where I want override certain properties of children. I have come to realize that the following pattern does exactly what I want:

this.props.children.map(child => 
    <child.type key={child.key} 
                ref={child.ref}
               {...child.props} 
               // add my props into children here
               data-leaving={true} />)

Instead of returning the child element, I return a new element of the same type and with the same props. I can then add or remove any props I want!

However, this is undocumented and feels very hacky. I would like to know if this is safe to use in every case.

Note that I am aware of alternatives (for example, accepting a function which returns the children instead of children directly) but this gives the most convenient interface by far.


回答1:


Best way to add new props or override existing ones is to map your children props and clone each element using React.cloneElement.

Nice article to read about react children.

React.Children.map(this.props.children, child =>
    React.cloneElement(child, { newProp: 'value', existingProp: 'value' }));

You could also use children as a function. This way u can also add your props.

Example:

// Root Component
const Parent = () => { 
  const onClose = () => console.log('I am on Close Prop');

  // Pass OnClose to children
  return <MyComponent>{ children(onClose) }</MyComponent>
}

// MyComponent
const MyComponent = () => {
// Pass OnClose to children
  return (
    <div>
      {/* children below */}
      {(onClose) => (
          <FormComponent
              myNewProp={onClose}
          />
      )}
    </div>
);

}


来源:https://stackoverflow.com/questions/50786382/how-to-safely-inject-props-into-react-children

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!