Accessing React component children props from the parent

前端 未结 4 1314
野的像风
野的像风 2021-01-07 16:36

I am currently in the process of designing the interface for a game engine that is written in JavaScript and ReactJS.

If a game object has a texture, the source of t

4条回答
  •  耶瑟儿~
    2021-01-07 17:22

    Is this the sort of thing you are thinking?

    const Game = ({
      children
    }) => {
      // small hack to turn single child, into array
      if (!children.length) {
        children = [children];
      }
    
      children.map((child, i) => {
        // now have access to props.source in parent
        console.log(child.props.source);
      })
    
      return ( < div > {
        children
      } < /div>
      );  
    }
    
    const Texture = ({source}) => {
      return (
        
    Texture: {source}
    ); } ReactDOM.render(( < Game > < Texture source = "thing.png" / > < Texture source = "other.png" / > < /Game> ), document.getElementById('game'));
    
    
    

    It's a little messy really.

    I would personally either give Game an array of textures to load itself.

    Or decouple Game and Texture entirely, so data flows only one way.

提交回复
热议问题