简体   繁体   English

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

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

I'm trying to pass props to my component children but I have this error : Unknown prop 'user' on tag. 我正在尝试将道具传递给我的组件子,但我有这个错误: 标签上的未知道具'用户'。 Remove this prop from the element. 从元素中删除此prop。

When looking at documentation and questions, I think I understood that props given to React.cloneElement (second argument) must be DOM recognized properties. 在查看文档和问题时,我想我理解为React.cloneElement(第二个参数)提供的道具必须是DOM识别的属性。

So my question is how to pass props to the component children and make them accessible in this.props ? 所以我的问题是如何将道具传递给组件子项并使它们在this.props中可访问?

Here is my code : 这是我的代码:

render() {

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

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

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

edit : the children component's propTypes 编辑:子组件的propTypes

ChildrenPage.propTypes = {
    user: PropTypes.object
}

export default ChildrenPage

Your code looks fine for me. 你的代码对我来说很好。 Usually, React give this warning when you are trying to render DOM element(Not a React Component) with invalid/non-standard DOM attribute. 通常,当您尝试使用无效/非标准DOM属性呈现DOM元素(非React组件)时,React会发出此警告。

In your case, this might happen if your children collection has a DOM element. 在你的情况,如果你的这件事会发生children集合有一个DOM元素。 Since user is not a standard DOM attribute, it might fire this warning when you are trying to clone the element with user prop. 由于user不是标准DOM属性,因此当您尝试使用user prop克隆元素时,它可能会触发此警告。

You can read more about this error here . 您可以在此处详细了解此错误。

Hope this helps! 希望这可以帮助!

Make sure that you are not passing down the children key as props. 确保您没有将子键作为道具传递下来。 Below code removes children key from props before passing it down to the children. 下面的代码会在将子项传递给子项之前从子项中删除子键。

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

This is one of the possible reasons. 这是可能的原因之一。 and, let me know if this solution works. 并且,如果此解决方案有效,请告诉我。 For more, https://facebook.github.io/react/warnings/unknown-prop.html 有关更多信息, 请访问https://facebook.github.io/react/warnings/unknown-prop.html

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

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