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

后端 未结 26 3431
猫巷女王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:09

    I needed to fix accepted answer above to make it work using that instead of this pointer. This within the scope of map function didn't have doSomething function defined.

    var Parent = React.createClass({
    doSomething: function() {
        console.log('doSomething!');
    },
    
    render: function() {
        var that = this;
        var childrenWithProps = React.Children.map(this.props.children, function(child) {
            return React.cloneElement(child, { doSomething: that.doSomething });
        });
    
        return 
    {childrenWithProps}
    }})

    Update: this fix is for ECMAScript 5, in ES6 there is no need in var that=this

提交回复
热议问题