Javascript 如何安全地向儿童注射道具?

Javascript 如何安全地向儿童注射道具?,javascript,reactjs,element,children,react-props,Javascript,Reactjs,Element,Children,React Props,我正在构建一个React组件,该组件延迟其子级的卸载,以便为它们设置动画。卸载时,我希望传入一个附加的道具(例如,数据属性或类名),以便处理动画 这是一般情况的一个特定实例,我希望覆盖子对象的某些属性。我逐渐意识到以下模式正是我想要的: this.props.children.map(child => <child.type key={child.key} ref={child.ref} {...child.p

我正在构建一个React组件,该组件延迟其子级的卸载,以便为它们设置动画。卸载时,我希望传入一个附加的道具(例如,数据属性或类名),以便处理动画

这是一般情况的一个特定实例,我希望覆盖子对象的某些属性。我逐渐意识到以下模式正是我想要的:

this.props.children.map(child => 
    <child.type key={child.key} 
                ref={child.ref}
               {...child.props} 
               // add my props into children here
               data-leaving={true} />)
this.props.children.map(child=>
)
我没有返回子元素,而是返回一个具有相同类型和道具的新元素。然后我可以添加或删除任何道具,我想

然而,这是没有文件记录的,感觉非常粗糙。我想知道在任何情况下使用它是否安全


请注意,我知道有其他选择(例如,接受一个返回子元素而不是直接返回子元素的函数),但这提供了迄今为止最方便的界面。

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

这篇文章很好读

您还可以使用子对象作为函数。这样你也可以添加你的道具

示例:

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

}
//根组件
常量父项=()=>{
const onClose=()=>console.log('I on Close Prop');
//传给孩子们
返回{children(onClose)}
}
//真菌成分
常量MyComponent=()=>{
//传给孩子们
返回(
{/*以下儿童*/}
{(onClose)=>(
)}
);
}

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

这篇文章很好读

您还可以使用子对象作为函数。这样你也可以添加你的道具

示例:

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

}
//根组件
常量父项=()=>{
const onClose=()=>console.log('I on Close Prop');
//传给孩子们
返回{children(onClose)}
}
//真菌成分
常量MyComponent=()=>{
//传给孩子们
返回(
{/*以下儿童*/}
{(onClose)=>(
)}
);
}