React - getting a component from a DOM element for debugging

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

    Here is a small snippet i'm currently using.

    It works with React 0.14.7.

    Gist with the code

    let searchRoot = ReactDom.render(ROOT, document.getElementById('main'));
    
    var getComponent = (comp) => comp._renderedComponent ? getComponent(comp._renderedComponent) : comp;
    
    var getComponentById = (id)=> {
      var comp = searchRoot._reactInternalInstance;
      var path = id.substr(1).split('.').map(a=> '.' + a);
      if (comp._rootNodeID !== path.shift()) throw 'Unknown root';
      while (path.length > 0) {
        comp = getComponent(comp)._renderedChildren[path.shift()];
      }
      return comp._instance;
    };
    
    window.$r = (node)=> getComponentById(node.getAttribute('data-reactid'))

    to run it, open Devtools, highlight an element you want to examine, and in the console type : $r($0)

提交回复
热议问题