简体   繁体   中英

ReactJS - How to get the whole render Tree

How do i access all the elements in the render tree of a react component, and no .props.children will not work nor can I use refs .

Here is an example of what I am trying to achieve.

// the following is the code inside the `render` function
// for a component called AwesomeLayer
// this.draw is the drawing function for ctx.
<LayoutLayer>
  <SomeOtherLayer>
    <Drawable onAnimationFrame={this.draw} />
  </SomeOtherLayer>
</LayoutLayer>

Now I have a top level container called SurfaceLayer The surface layer is supposed to visit all its child elements one after the other on propsChange and then find all the drawables and cache that response for future rafs on any update this is purged.

But if the SurfaceLayer is composed like the following

<SurfaceLayer>
    <AwesomeLayer />
</SurfaceLayer>

I won't get reference to the drawable, because the children of the AwesomeLayer node will be undefined. PS This code may be used by others and so I would not rely on explicit refs as they will cause more errors.

How i have done it now is I mantain a singleton store for the whole UI layer which keeps a reference to all the ui elements, (which I feel is bad), is there a better way to do this ?

What you need is a little bit against the react.js flow, where you propagate updates in a top-down manner, without needing to worry about the actual children. Also it seems you are trying to access refs from an ancestor of the element rather than from its parent, which might not be that easy. What you can do is to add a ref to AwesomeLayer and ask that ref about its children, for example by adding a getAwesomeChildren() method to the AwesomeLayer component.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM