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

IT技术 javascript reactjs
2021-04-29 15:12:25

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

在查看文档和问题时,我想我明白给 React.cloneElement(第二个参数)的 props 必须是 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>
    )
}

编辑:子组件的 propTypes

ChildrenPage.propTypes = {
    user: PropTypes.object
}

export default ChildrenPage
2个回答

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

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

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

希望这可以帮助!

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

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