React.cloneElement: pass new children or copy props.children?

北战南征 提交于 2019-12-08 17:05:46

问题


I'm confused by the third "children" parameter of React.cloneElement and it's relation to this.props.children.

I followed this guide on higher order components and have the following code:

render() {
    const elementsTree = super.render()

    let myPropChange = {}

    /* work on newProps... */
    myPropChange.something = "nice!".

    const newProps = Object.assign({}, elementsTree.props, myPropChange)

    /* map children */
    const newChildren = React.Children.map(elementsTree.props.children, c => something(c))

    return React.cloneElement(elementsTree, newProps, newChildren)
}
  • Should I put the mapped children into my newProps.children or should I pass them as the third parameter to cloneElement?

  • Object.assign copied the children from props to newProps anyway, should I skip them?

  • In the guide it says

    Components don’t have a guaranty of having the full children tree resolved.

    What does that mean in my situation? That this.props.children is not there?

  • Added 4th question: Why should I clone the props at all and not just directly edit them?


回答1:


Should I put the mapped children into my newProps.children or should I pass them as the third parameter to cloneElement?

Either should be fine.

Object.assign copied the children from props to newProps anyway, should I skip them?

When using cloneElement, you don't need to copy the props yourself. You can just do React.cloneElement(elementsTree, {something: 'nice!'}).

In the guide it says "Components don’t have a guaranty of having the full children tree resolved." What does that mean in my situation? That this.props.children is not there?

I can't be sure what that article meant, but I believe the author means that your component can choose not to use this.props.children. For example, if you render <Foo><Bar /></Foo>, then Foo will receive <Bar /> in this.props.children, but if Foo doesn't use this.props.children in its render method, then Bar will never be rendered.

Why should I clone the props at all and not just directly edit them?

React elements are immutable and there's no way you can change the props after an element is created. This allows some performance optimizations in React which wouldn't be possible otherwise.



来源:https://stackoverflow.com/questions/37120956/react-cloneelement-pass-new-children-or-copy-props-children

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!