简体   繁体   English

使用React.cloneElement将道具传递给孩子

[英]passing props to childrens using React.cloneElement

You can do this 你可以这样做

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

to pass props to MyComponent, but if you want to make MyComponent as a children you have to use 将道具传递给MyComponent,但是如果要将MyComponent作为孩子,则必须使用

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

Is there any alternative to cloneElement? 有没有替代cloneElement的选择? I'm using babel I try not to write in older way. 我正在使用babel,我尽量不要以较旧的方式编写。

The props object is read only, which means something like this.props.children[0].props = {...} will not work. props对象是只读的,这意味着类似this.props.children[0].props = {...}将无法工作。 You must use React.cloneElement . 您必须使用React.cloneElement

https://facebook.github.io/react/docs/components-and-props.html#props-are-read-only https://facebook.github.io/react/docs/components-and-props.html#props-are-read-only

React is pretty flexible but it has a single strict rule: React非常灵活,但是它有一个严格的规则:

All React components must act like pure functions with respect to their props. 就其道具而言,所有React组件都必须像纯函数一样工作。

If you have a component reading and manipulating the props of it's child, the child may not be pure anymore. 如果您有阅读和操纵其孩子的道具的组件,则该孩子可能不再纯洁。 So you need to clone a new one. 因此,您需要克隆一个新的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM