通过DOM节点获取React组件数据

    技术2022-07-11  129

    Retrieving a React component's DOM node is fairly simple from within the component itself, but what if you want to work backward:  retrieve a component's instance by DOM node?  This is a task that the old Dojo Toolkit's Dijit framework allowed with the dijit.byId method, so it made me think if you could do the same with React.  It turns out you can retrieve a component instance by DOM node!

    从组件本身内部检索React组件的DOM节点非常简单,但是如果您想向后工作怎么办:按DOM节点检索组件的实例呢? 这是旧的Dojo Toolkit的Dijit框架使用dijit.byId方法所允许的dijit.byId ,因此它使我思考是否可以使用React进行相同的操作。 事实证明,您可以按DOM节点检索组件实例!

    The following function allows you to get a React component instance by DOM node:

    以下函数允许您通过DOM节点获取React组件实例:

    function findReactElement(node) { for (var key in node) { if (key.startsWith("__reactInternalInstance$")) { return node[key]._debugOwner.stateNode; } } return null; }

    If the node is a React component root, you'll see a load of amazing information, like its props, state, context, refs, list of methods, and more:

    如果该节点是React组件的根,您将看到大量令人惊奇的信息,例如其属性,状态,上下文,引用,方法列表等:

    Modifying props/state and calling render methods don't appear to actually do anything, so manipulation doesn't look possible from the outside, but it is useful to be able to get the component instance based on DOM node if for nothing other than inspection.  Nice!

    修改道具/状态和调用渲染方法似乎实际上并没有执行任何操作,因此从外部看似乎无法进行操作,但是如果仅需检查,便能够基于DOM节点获取组件实例非常有用。 。 真好!

    翻译自: https://davidwalsh.name/get-react-component-by-dom-node

    相关资源:jdk-8u281-windows-x64.exe
    Processed: 0.012, SQL: 10