【问题标题】:React.cloneElement: pass new children or copy props.children?React.cloneElement:传递新的孩子还是复制 props.children?
【发布时间】:2016-05-09 16:33:47
【问题描述】:

我对@9​​87654322@ 的第三个“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)
}
  • 我应该将映射的子级放入我的newProps.children 还是应该将它们作为第三个参数传递给cloneElement

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

  • 在指南中说

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

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

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

【问题讨论】:

    标签: javascript reactjs higher-order-functions


    【解决方案1】:

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

    应该没问题。

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

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

    在指南中它说“组件不保证解决完整的子树。”在我的情况下这意味着什么?那个 this.props.children 不存在?

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

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

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

    【讨论】:

    • 那么两个后续问题: 1、如果cloneElement把传过来的props和老的props合并了,如果我通过React.cloneElement(elementsTree, {children: ELEMENT}会发生什么老子代被替换?
    • 2. “创建元素后,您无法更改道具。”那么我可以直接在我的 HOC-render 方法中编辑 props 对象,并添加键/值吗?
    • 1.是的,他们会的。 2.不,this.props是一个冻结对象。
    • 如果我没有传递任何第三个参数并且在我的新道具中没有 children 属性,孩子不会被复制,这是正确的行为吗?我以为它们是道具的一部分……
    猜你喜欢
    • 2020-05-27
    • 2017-02-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-09
    • 2013-05-03
    • 2013-01-21
    • 2016-10-26
    • 1970-01-01
    相关资源
    最近更新 更多