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

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

    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 (
           
             {this.props.children}
           
        );
      }
    }
    
    class Child extends React.Component {
      static contextType = MyContext;
    
      onClick = () => {
        this.context.doSomething(this.props.value);
      };      
    
      render() {
        return (
          
    {this.props.value}
    ); } } // Example of using Parent and Child import * as React from 'react'; class SomeComponent extends React.Component { render() { return ( ); } }

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

    class SomeComponent extends React.Component {
    
      render() {
        return (
          
            
            
          
        );
      }
    }
    

提交回复
热议问题