React - getting a component from a DOM element for debugging

前端 未结 10 1055
广开言路
广开言路 2020-11-28 19:02

For the purposes of debugging in the console, is there any mechanism available in React to use a DOM element instance to get the backing React component?

This questi

10条回答
  •  南笙
    南笙 (楼主)
    2020-11-28 19:59

    React 16+ version:

    If you want the nearest React component instance that the selected DOM element belongs to, here's how you can find it (modified from @Guan-Gui's solution):

    window.getComponentFromElement = function(el) {
      for (const key in el) {
        if (key.startsWith('__reactInternalInstance$')) {
          const fiberNode = el[key];
          return fiberNode && fiberNode._debugOwner && fiberNode._debugOwner.stateNode;
        }
      }
      return null;
    };
    

    They trick here is to use the _debugOwner property, which is a reference to the FiberNode of the nearest component that the DOM element is part of.

    Caveat: Only running in dev mode will the components have the _debugOwner property. This would not work in production mode.

    Bonus

    I created this handy snippet that you can run in your console so that you can click on any element and get the React component instance it belongs to.

    document.addEventListener('click', function(event) {
      const el = event.target;
      for (const key in el) {
        if (key.startsWith('__reactInternalInstance$')) {
          const fiberNode = el[key];
          const component = fiberNode && fiberNode._debugOwner;
          if (component) {
            console.log(component.type.displayName || component.type.name);
            window.$r = component.stateNode;
          }
          return;
        }
      }
    });
    

提交回复
热议问题