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

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

    Cloning children with new props

    You can use React.Children to iterate over the children, and then clone each element with new props (shallow merged) using React.cloneElement. For example:

    const Child = ({ doSomething, value }) => (
        <button onClick={() => doSomething(value)}>Click Me</button>
    );
    
    class Parent extends React.Component{
        doSomething = value => {
            console.log("doSomething called by child with value:", value);
        }
    
        render() {
            const childrenWithProps = React.Children.map(this.props.children, child => {
                // checking isValidElement is the safe way and avoids a typescript error too
                const props = { doSomething };
                if (React.isValidElement(child)) {
                    return React.cloneElement(child, props);
                }
                return child;
            });
    
            return <div>{childrenWithProps}</div>;
        }
    }
    
    function App() {
        return (
            <Parent>
                <Child value={1} />
                <Child value={2} />
            </Parent>
        );
    }
    
    ReactDOM.render(<App />, document.getElementById("container"));
    

    Fiddle: https://jsfiddle.net/2q294y43/2/

    Calling children as a function

    Alternatively, you can pass props to children with render props. In this approach, the children (which can be children or any other prop name) is a function which can accept any arguments you want to pass and returns the children:

    const Child = ({ doSomething, value }) => (
        <button onClick={() => doSomething(value)}>Click Me</button>
    );
    
    class Parent extends React.Component{
        doSomething = value => {
            console.log("doSomething called by child with value:", value);
        }
    
        render(){
            // note that children is called as a function and we can pass args to it
            return <div>{this.props.children(doSomething)}</div>
        }
    };
    
    function App(){
        return (
            <Parent>
                {doSomething => (
                    <React.Fragment>
                        <Child doSomething={doSomething} value={1} />
                        <Child doSomething={doSomething} value={2} />
                    </React.Fragment>
                )}
            </Parent>
        );
    }
     
    ReactDOM.render(<App />, document.getElementById("container"));
    

    Instead of <React.Fragment> or simply <> you can also return an array if you prefer.

    Fiddle: https://jsfiddle.net/ferahl/y5pcua68/7/

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

    Passing Props to Nested Children

    With the update to React 16.6 you can now use React.createContext and contextType.

    import * as React from 'react';
    
    // React.createContext accepts a defaultValue as the first param
    const MyContext = React.createContext(); 
    
    class Parent extends React.Component {
      doSomething = (value) => {
        // Do something here with value
      };
    
      render() {
        return (
           <MyContext.Provider value={{ doSomething: this.doSomething }}>
             {this.props.children}
           </MyContext.Provider>
        );
      }
    }
    
    class Child extends React.Component {
      static contextType = MyContext;
    
      onClick = () => {
        this.context.doSomething(this.props.value);
      };      
    
      render() {
        return (
          <div onClick={this.onClick}>{this.props.value}</div>
        );
      }
    }
    
    
    // Example of using Parent and Child
    
    import * as React from 'react';
    
    class SomeComponent extends React.Component {
    
      render() {
        return (
          <Parent>
            <Child value={1} />
            <Child value={2} />
          </Parent>
        );
      }
    }
    

    React.createContext shines where React.cloneElement case couldn't handle nested components

    class SomeComponent extends React.Component {
    
      render() {
        return (
          <Parent>
            <Child value={1} />
            <SomeOtherComp><Child value={2} /></SomeOtherComp>
          </Parent>
        );
      }
    }
    
    0 讨论(0)
  • 2020-11-22 00:20

    I came to this post while researching for a similar need, but i felt cloning solution that is so popular, to be too raw and takes my focus away from the functionality.

    I found an article in react documents Higher Order Components

    Here is my sample:

    import React from 'react';
    
    const withForm = (ViewComponent) => {
        return (props) => {
    
            const myParam = "Custom param";
    
            return (
                <>
                    <div style={{border:"2px solid black", margin:"10px"}}>
                        <div>this is poc form</div>
                        <div>
                            <ViewComponent myParam={myParam} {...props}></ViewComponent>
                        </div>
                    </div>
                </>
            )
        }
    }
    
    export default withForm;
    
    
    const pocQuickView = (props) => {
        return (
            <div style={{border:"1px solid grey"}}>
                <div>this is poc quick view and it is meant to show when mouse hovers over a link</div>
            </div>
        )
    }
    
    export default withForm(pocQuickView);
    

    For me i found a flexible solution in implementing the pattern of Higher Order Components.

    Of course it depends on the functionality, but it is good if someone else is looking for a similar requirement, it is much better than being dependent on raw level react code like cloning.

    Other pattern that i actively use is the container pattern. do read about it, there are many articles out there.

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

    You can use React.cloneElement, it's better to know how it works before you start using it in your application. It's introduced in React v0.13, read on for more information, so something along with this work for you:

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

    So bring the lines from React documentation for you to understand how it's all working and how you can make use of them:

    In React v0.13 RC2 we will introduce a new API, similar to React.addons.cloneWithProps, with this signature:

    React.cloneElement(element, props, ...children);
    

    Unlike cloneWithProps, this new function does not have any magic built-in behavior for merging style and className for the same reason we don't have that feature from transferPropsTo. Nobody is sure what exactly the complete list of magic things are, which makes it difficult to reason about the code and difficult to reuse when style has a different signature (e.g. in the upcoming React Native).

    React.cloneElement is almost equivalent to:

    <element.type {...element.props} {...props}>{children}</element.type>
    

    However, unlike JSX and cloneWithProps, it also preserves refs. This means that if you get a child with a ref on it, you won't accidentally steal it from your ancestor. You will get the same ref attached to your new element.

    One common pattern is to map over your children and add a new prop. There were many issues reported about cloneWithProps losing the ref, making it harder to reason about your code. Now following the same pattern with cloneElement will work as expected. For example:

    var newChildren = React.Children.map(this.props.children, function(child) {
      return React.cloneElement(child, { foo: true })
    });
    

    Note: React.cloneElement(child, { ref: 'newRef' }) DOES override the ref so it is still not possible for two parents to have a ref to the same child, unless you use callback-refs.

    This was a critical feature to get into React 0.13 since props are now immutable. The upgrade path is often to clone the element, but by doing so you might lose the ref. Therefore, we needed a nicer upgrade path here. As we were upgrading callsites at Facebook we realized that we needed this method. We got the same feedback from the community. Therefore we decided to make another RC before the final release to make sure we get this in.

    We plan to eventually deprecate React.addons.cloneWithProps. We're not doing it yet, but this is a good opportunity to start thinking about your own uses and consider using React.cloneElement instead. We'll be sure to ship a release with deprecation notices before we actually remove it so no immediate action is necessary.

    more here...

    0 讨论(0)
  • 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 <div>{childrenWithProps}</div>
    
    }
    
    0 讨论(0)
  • 2020-11-22 00:23

    I think a render prop is the appropriate way to handle this scenario

    You let the Parent provide the necessary props used in child component, by refactoring the Parent code to look to something like this:

    const Parent = ({children}) => {
      const doSomething(value) => {}
    
      return children({ doSomething })
    }
    

    Then in the child Component you can access the function provided by the parent this way:

    class Child extends React {
    
      onClick() => { this.props.doSomething }
    
      render() { 
        return (<div onClick={this.onClick}></div>);
      }
    
    }
    

    Now the fianl stucture will look like this:

    <Parent>
      {(doSomething) =>
       (<Fragment>
         <Child value="1" doSomething={doSomething}>
         <Child value="2" doSomething={doSomething}>
        <Fragment />
       )}
    </Parent>
    
    0 讨论(0)
提交回复
热议问题