Javascript 使用React.cloneElement向儿童传递道具

Javascript 使用React.cloneElement向儿童传递道具,javascript,reactjs,Javascript,Reactjs,你可以这样做 <div> <MyComponent ...this.props/> </div> 要将道具传递给MyComponent,但如果您想让MyComponent成为儿童,则必须使用 <div>{React.cloneElement(this.props.children, this.props)}</div> {React.cloneElement(this.props.children,this.props)} 除

你可以这样做

<div>
<MyComponent ...this.props/>
</div>

要将道具传递给MyComponent,但如果您想让MyComponent成为儿童,则必须使用

<div>{React.cloneElement(this.props.children, this.props)}</div>
{React.cloneElement(this.props.children,this.props)}

除了cloneElement还有其他选择吗?我使用的是babel,我尽量不以旧的方式编写。props对象是只读的,这意味着类似于
this.props.children[0]。props={…}
的东西将不起作用。您必须使用
React.cloneElement

React非常灵活,但有一条严格的规则:

所有React组件在其道具方面都必须像纯函数一样工作。


如果您有一个组件读取和操作其子组件的道具,则该子组件可能不再是纯粹的。所以你需要克隆一个新的。

你想要实现什么?您想在
div
中呈现
MyComponent
并传递
道具
?如果您想做的是将道具传递给已经呈现的子级,那么是的,您必须克隆它并传递新的道具。@ndugger React.cloneElement的新语法是什么?为什么您认为有“新语法”要替换它?@MayankShukla传递道具并将其渲染为儿童?