繁体   English   中英

如何使用React.cloneElement将道具传递给孩子?

[英]how to pass props to children with React.cloneElement?

我正在尝试将道具传递给我的组件子,但我有这个错误: 标签上的未知道具'用户'。 从元素中删除此prop。

在查看文档和问题时,我想我理解为React.cloneElement(第二个参数)提供的道具必须是DOM识别的属性。

所以我的问题是如何将道具传递给组件子项并使它们在this.props中可访问?

这是我的代码:

render() {

    const { children } = this.props
    const { user } = this.state

    const childrenWithProps = React.Children.map(children, child =>
        React.cloneElement(child, { user })    
    )

    return (
        <div>
            { childrenWithProps }
        </div>
    )
}

编辑:子组件的propTypes

ChildrenPage.propTypes = {
    user: PropTypes.object
}

export default ChildrenPage

你的代码对我来说很好。 通常,当您尝试使用无效/非标准DOM属性呈现DOM元素(非React组件)时,React会发出此警告。

在你的情况,如果你的这件事会发生children集合有一个DOM元素。 由于user不是标准DOM属性,因此当您尝试使用user prop克隆元素时,它可能会触发此警告。

您可以在此处详细了解此错误。

希望这可以帮助!

确保您没有将子键作为道具传递下来。 下面的代码会在将子项传递给子项之前从子项中删除子键。

let key = 'children';
let {[key]: _, ...newProps} = state;
{React.Children.map(this.props.children, child => 
  React.cloneElement(child, {...newProps}))}

这是可能的原因之一。 并且,如果此解决方案有效,请告诉我。 有关更多信息, 请访问https://facebook.github.io/react/warnings/unknown-prop.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM