How to pass props to {this.props.children}

后端 未结 26 3415
猫巷女王i
猫巷女王i 2020-11-21 23:42

I\'m trying to find the proper way to define some components which could be used in a generic way:


  
  

        
26条回答
  •  清酒与你
    2020-11-22 00:15

    If you have multiple children you want to pass props to, you can do it this way, using the React.Children.map:

    render() {
        let updatedChildren = React.Children.map(this.props.children,
            (child) => {
                return React.cloneElement(child, { newProp: newProp });
            });
    
        return (
            
    { updatedChildren }
    ); }

    If your component is having just one child, there's no need for mapping, you can just cloneElement straight away:

    render() {
        return (
            
    { React.cloneElement(this.props.children, { newProp: newProp }) }
    ); }

提交回复
热议问题