React - getting a component from a DOM element for debugging

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

    I've adapted @Venryx's answer with a slightly adapted ES6 version that fit my needs. This helper function returns the current element instead of the _owner._instance property.

    getReactDomComponent(dom) {
      const internalInstance = dom[Object.keys(dom).find(key =>
        key.startsWith('__reactInternalInstance$'))];
      if (!internalInstance) return null;
      return internalInstance._currentElement;
    }
    

提交回复
热议问题