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

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

    Parent.jsx:

    import React from 'react';
    
    const doSomething = value => {};
    
    const Parent = props => (
      
    { !props || !props.children ?
    Loading... (required at least one child)
    : !props.children.length ? {props.children} : props.children.map((child, key) => React.cloneElement(child, {...props, key, doSomething})) }
    );

    Child.jsx:

    import React from 'react';
    
    /* but better import doSomething right here,
       or use some flux store (for example redux library) */
    export default ({ doSomething, value }) => (
      
    doSomething(value)}/> );

    and main.jsx:

    import React from 'react';
    import { render } from 'react-dom';
    import Parent from './Parent';
    import Child from './Child';
    
    render(
      
        
        
        
      ,
      document.getElementById('...')
    );
    

    see example here: https://plnkr.co/edit/jJHQECrKRrtKlKYRpIWl?p=preview

提交回复
热议问题