React.cloneElement:传递新的孩子或复制props.children?

Fab*_*ndl 8 javascript higher-order-functions reactjs

我很困惑第三个"儿童"参数React.cloneElement和它的关系this.props.children.

我在高阶组件上遵循了本指南,并具有以下代码:

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)
}
Run Code Online (Sandbox Code Playgroud)
  • 我应该将映射的孩子放入我的newProps.children或者我应该将它们作为第三个参数传递给我cloneElement吗?

  • Object.assign无论如何都要将孩子复制propsnewProps我这里,我应该跳过它们吗?

  • 在指南中说

    组件无法保证解析完整的子树.

    这在我的情况下意味着什么?那this.props.children不是吗?

  • 添加了第4个问题:为什么我要克隆道具而不是直接编辑它们?

Sop*_*ert 7

我应该将映射的孩子放入我的newProps.children或者我应该将它们作为第三个参数传递给我cloneElement吗?

要么应该没事.

Object.assign无论如何都要将孩子复制propsnewProps我这里,我应该跳过它们吗?

使用cloneElement时,您不需要自己复制道具.你可以这样做React.cloneElement(elementsTree, {something: 'nice!'}).

在指南中,它说"组件没有保证解决完整的子树".这在我的情况下意味着什么?那个.props.children不在吗?

我无法确定该文章的含义,但我相信作者意味着您的组件可以选择不使用this.props.children.例如,如果渲染<Foo><Bar /></Foo>,Foo则会接收<Bar />this.props.children,但如果Foo不在this.props.children其渲染方法中使用,则Bar永远不会渲染.

我为什么要克隆道具而不是直接编辑它们?

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

  • 是的,他们愿意.不,`this.props`是一个冻结的对象. (2认同)