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

imr*_*rok 5 javascript reactjs

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

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

所以我的问题是如何将 props 传递给组件子组件并使它们在 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>
    )
}
Run Code Online (Sandbox Code Playgroud)

编辑:子组件的 propTypes

ChildrenPage.propTypes = {
    user: PropTypes.object
}

export default ChildrenPage
Run Code Online (Sandbox Code Playgroud)

Cha*_*aur 0

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

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

这是可能的原因之一。并且,让我知道这个解决方案是否有效。有关更多信息,https://facebook.github.io/react/warnings/unknown-prop.html