本文介绍了如何使用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.

在查看文档和问题时,我想我明白给予React.cloneElement(第二个参数)的道具必须是DOM识别属性。

When looking at documentation and questions, I think I understood that props given to React.cloneElement (second argument) must be DOM recognized properties.

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

So my question is how to pass props to the component children and make them accessible in 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

edit : the children component's propTypes

ChildrenPage.propTypes = {
    user: PropTypes.object
}

export default ChildrenPage


推荐答案

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

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.

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

In your case, this might happen if your children collection has a DOM element. Since user is not a standard DOM attribute, it might fire this warning when you are trying to clone the element with user prop.

您可以阅读有关此错误的更多信息。

You can read more about this error here.

希望这有帮助!

这篇关于如何使用React.cloneElement将道具传递给孩子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 11:16