React.cloneElement:传递新的children还是复制props.children?

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

我对 React.cloneElement 的第三个 "children" 参数感到困惑,它与 this.props.children 的关系。

我在高阶组件上遵循 this guide 并具有以下代码:

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?

使用cloneElement时,不需要自己复制props。你可以做 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?

我不能确定那篇文章的意思,但我相信作者的意思是你的组件可以选择不使用this.props.children。例如,如果您渲染 <Foo><Bar /></Foo>,那么 Foo 将在 this.props.children 中接收 <Bar />,但如果 Foo 不在其中使用 this.props.children render 方法,那么 Bar 将永远不会被渲染。

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

React 元素是不可变的,您无法在创建元素后更改道具。这允许在 React 中进行一些性能优化,否则是不可能的。