简体   繁体   English

ReactJS - 如何获取整个渲染树

[英]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 . 我如何访问react组件的渲染树中的所有元素,没有.props.children不能工作,也不能使用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. 现在我有一个名为SurfaceLayer的顶级容器表面层应该在propsChange上一个接一个地访问它的所有子元素,然后找到所有drawable并在任何更新清除后为未来的raf缓存该响应。

But if the SurfaceLayer is composed like the following 但是如果SurfaceLayer的组成如下

<SurfaceLayer>
    <AwesomeLayer />
</SurfaceLayer>

I won't get reference to the drawable, because the children of the AwesomeLayer node will be undefined. 我不会引用drawable,因为AwesomeLayer节点的子节点将是未定义的。 PS This code may be used by others and so I would not rely on explicit refs as they will cause more errors. PS此代码可能被其他人使用,因此我不会依赖显式引用,因为它们会导致更多错误。

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 ? 我现在如何做到这一点是我为整个UI层保留了一个单独的store ,它保留了对所有ui元素的引用(我感觉很糟糕),有没有更好的方法来做到这一点?

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. 你需要的是对react.js流的一点点,你可以用自上而下的方式传播更新,而不必担心实际的孩子。 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. 您可以做的是向AwesomeLayer添加一个引用并询问有关其子代的引用,例如通过向AwesomeLayer组件添加getAwesomeChildren()方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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