简体   繁体   English

React - 从子DOM元素中获取React组件?

[英]React - get React component from a child DOM element?

I'd like to be able to figure out what React component is associated with a certain DOM element. 我希望能够弄清楚React组件与某个DOM元素的关联。

For example, say I have a div, and I'm rendering my entire application using React. 例如,假设我有一个div,并且我使用React渲染我的整个应用程序。 The div has to be rendered by a React component - but which one? div必须由React组件呈现 - 但是哪一个?

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. 我知道React提供方法“ getDOMNode ”来获取与React组件关联的DOM节点,但我想做相反的事情。

Is this possible? 这可能吗?

No. 没有。

A central concept in React is that you don't actually have a control in the DOM. React的一个核心概念是你实际上没有DOM中的控件。 Instead, your control is that factory function. 相反,您的控制是工厂功能。 What's in the DOM is the current render of the control. DOM中的内容是控件的当前呈现。

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. 如果确实需要这个,可以将对象保存为全局变量,其键是工厂函数名称的字符串表示形式,其值是工厂函数,然后在可渲染div上保留包含名称的属性工厂功能。

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. 但很有可能这是XY问题的问题(需要X,看Y的方式,然后询问如何做Y)。可能如果你解释你的目标,那么更好的方法更适合React的自上而下的概念模型。

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. 一般来说,要求从其渲染中访问控件就像是要求从其缓存的PNG渲染中访问SVG。 It's possible, but it's usually a red flag that something else is conceptually wrong. 这是可能的,但它通常是一个红旗,其他东西在概念上是错误的。

Here's what I use, with React 15.3.0: 以下是我使用的React 15.3.0:

window.FindReact = function(dom) {
    for (var key in dom) {
        if (key.startsWith("__reactInternalInstance$")) {
            var compInternals = dom[key]._currentElement;
            var compWrapper = compInternals._owner;
            var comp = compWrapper._instance;
            return comp;
        }
    }
    return null;
};

And then to use it: 然后使用它:

var someElement = document.getElementById("someElement");
FindReact(someElement).setState({test1: test2});

If your situtation demands getting react element from DOM node, here is an approach, "Communicate via event and call back" 如果你的situtation要求从DOM节点获取react元素,这里有一种方法,“通过事件和回调进行通信”

You shall fire a custom event on DOM element and have event listener for that custom event in React component. 您将在DOM元素上触发自定义事件,并在React组件中为该自定义事件提供事件侦听器。 This will map DOM element back to react component. 这会将DOM元素映射回反应组件。

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

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