React - getting a component from a DOM element for debugging

前端 未结 10 1033
广开言路
广开言路 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:47

    Here you go. This supports React 16+

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

提交回复
热议问题