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

后端 未结 26 3417
猫巷女王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 <div>{childrenWithProps}</div>
    }})
    

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

    0 讨论(0)
  • 2020-11-22 00:10

    Maybe you can also find useful this feature, though many people have considered this as an anti-pattern it still can be used if you're know what you're doing and design your solution well.

    Function as Child Components

    0 讨论(0)
  • 2020-11-22 00:10

    For any one who has a single child element this should do it.

    {React.isValidElement(this.props.children)
                      ? React.cloneElement(this.props.children, {
                          ...prop_you_want_to_pass
                        })
                      : null}
    
    0 讨论(0)
  • 2020-11-22 00:11

    When using functional components, you will often get the TypeError: Cannot add property myNewProp, object is not extensible error when trying to set new properties on props.children. There is a work around to this by cloning the props and then cloning the child itself with the new props.

    const MyParentComponent = (props) => {
      return (
        <div className='whatever'>
          {props.children.map((child) => {
            const newProps = { ...child.props }
            // set new props here on newProps
            newProps.myNewProp = 'something'
            const preparedChild = { ...child, props: newProps }
            return preparedChild
          })}
        </div>
      )
    }
    
    0 讨论(0)
  • 2020-11-22 00:11

    The slickest way to do this:

        {React.cloneElement(this.props.children, this.props)}
    
    0 讨论(0)
  • 2020-11-22 00:12

    For a slightly cleaner way to do it, try:

    <div>
        {React.cloneElement(this.props.children, { loggedIn: this.state.loggedIn })}
    </div>
    

    Edit: To use with multiple individual children (the child must itself be a component) you can do. Tested in 16.8.6

    <div>
        {React.cloneElement(props.children[0], { loggedIn: true, testingTwo: true })}
        {React.cloneElement(props.children[1], { loggedIn: true, testProp: false })}
    </div>
    
    0 讨论(0)
提交回复
热议问题