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

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

本文关键字:孩子 复制 props children cloneElement React      更新时间:2023-09-26

我被React.cloneElement的第三个"children"参数以及它与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)
}
  • 我应该将映射的子项放入newProps.children中,还是将它们作为第三个参数传递给cloneElement

  • Object.assign将孩子从props复制到newProps,我应该跳过它们吗?

  • 指南上写着

    组件不能保证解决完整的子树。

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

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

我应该将映射的子项放入newProps.children中,还是将它们作为第三个参数传递给cloneElement

两者都应该可以。

Object.assign将孩子从props复制到newProps,我应该跳过它们吗?

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

在指南中,它说"组件不能保证完整的子树得到解决。"在我的情况下,这意味着什么?这个孩子不在那里?

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

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

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