如何安全地将道具注入React儿童? [英] How to safely inject props into React children?

查看:64
本文介绍了如何安全地将道具注入React儿童?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个React组件,该组件会延迟其子项的卸载以为其设置动画。卸载时,我想传入一个额外的道具(例如,数据属性或类名)以处理动画。

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!

但是,这没有记载,感觉很hacky。我想知道是否在每种情况下都可以安全使用。

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.

推荐答案

添加新道具或覆盖现有道具的最佳方法是映射子道具。并使用 React.cloneElement 克隆每个元素。

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.

示例:

// 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>
);

}

这篇关于如何安全地将道具注入React儿童?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆