yaw*_*awn 0 javascript children element reactjs react-props
我正在构建一个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} />)
Run Code Online (Sandbox Code Playgroud)
我没有返回子元素,而是返回了一个具有相同类型和相同道具的新元素。然后,我可以添加或删除我想要的任何道具!
但是,这没有记录,并且感觉很hacky。我想知道这是否在每种情况下都可以安全使用。
请注意,我知道其他方法(例如,接受一个可以直接返回子级而不是子级的函数),但这提供了迄今为止最方便的接口。
添加新道具或覆盖现有道具的最佳方法是映射子道具并使用克隆每个元素React.cloneElement。
阅读关于反应孩子的好文章。
React.Children.map(this.props.children, child =>
React.cloneElement(child, { newProp: 'value', existingProp: 'value' }));
Run Code Online (Sandbox Code Playgroud)
您还可以将子级用作功能。这样,您还可以添加道具。
例:
// 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>
);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4117 次 |
| 最近记录: |