React - 从子DOM元素获取React组件? [英] React - get React component from a child DOM element?

查看:86
本文介绍了React - 从子DOM元素获取React组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道React组件是否与某个DOM元素相关联。



例如,说我有一个div,而我'使用React渲染我的整个应用程序。 div必须由React组件渲染 - 但是哪一个?



我知道React提供了 getDOMNode 来获取与React组件关联的DOM节点,但是我想做相反。



这是可能吗?

解决方案



React中的一个中心概念是,在DOM中实际上并不具有控制权。相反,您的控制是工厂功能。 DOM中的内容是控件的当前渲染。



如果您真的需要这个,可以将对象保留为全局变量,其中的关键字是工厂功能的名称,其值是工厂功能,然后在可渲染的div上,保留包含工厂功能名称的属性。



但是这可能是是一个问题的XY问题(需要X,看到一个方式与Y,然后问如何做Y.)可能如果你解释你的目标,有一个更好的方式更好地适应React的自上而下的概念模型。 >

一般来说,要求从其渲染中访问控件就像要求从缓存的PNG渲染中访问SVG。这是可能的,但它通常是一个红旗,其他东西在概念上是错误的。


I'd like to be able to figure out what React component is associated with a certain DOM element.

For example, say I have a div, and I'm rendering my entire application using React. The div has to be rendered by a React component - but which one?

I know that React supplies the method "getDOMNode" to get the DOM node associated with a React component, but I'd like to do the opposite.

Is this possible?

解决方案

No.

A central concept in React is that you don't actually have a control in the DOM. Instead, your control is that factory function. What's in the DOM is the current render of the control.

If you actually need this, you can keep an object as a global variable, whose keys are the string representations of the names of factory functions, and whose values are the factory functions, then on your renderable div, keep an attribute containing the name of the factory function.

But chances are this is a question of the XY problem (needing X, seeing a way with Y, then asking how to do Y.) Probably if you'd explain your goal there's a better way that better fits React's top-down conceptual model.

Generally speaking, asking to get access to the control from its render is like asking to get access to an SVG from its cached PNG render. It's possible, but it's usually a red flag that something else is conceptually wrong.

这篇关于React - 从子DOM元素获取React组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆