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

后端 未结 26 3498
猫巷女王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条回答
  •  梦毁少年i
    2020-11-22 00:21

    None of the answers address the issue of having children that are NOT React components, such as text strings. A workaround could be something like this:

    // Render method of Parent component
    render(){
        let props = {
            setAlert : () => {alert("It works")}
        };
        let childrenWithProps = React.Children.map( this.props.children, function(child) {
            if (React.isValidElement(child)){
                return React.cloneElement(child, props);
            }
              return child;
          });
        return 
    {childrenWithProps}
    }

提交回复
热议问题