Is it possible to retrieve a component's instance from a React Fiber?

微笑、不失礼 提交于 2020-01-23 12:11:00

问题


Before v16 of React -- that is, before the introduction of React fibers -- it was possible to take a DOM element and retrieve the React component instance as follows:

const getReactComponent = dom => {
  let found = false;
  const keys = Object.keys(dom);

  keys.forEach(key => {
    if (key.startsWith('__reactInternalInstance$')) {
      const compInternals = dom[key]._currentElement;
      const compWrapper = compInternals._owner;
      const comp = compWrapper._instance;
      found = comp;
    }
  });

  return found || null;
};

This no longer works for React v16, which uses the new Fiber implementation. Specifically, the above code throws an error at the line const comparWrapper = compInternals._owner because there is no _owner property anymore. Thus you cannot also access the _instance.

My question here is how would we retrieve the instance from a DOM element in v16's Fiber implementation?


回答1:


You may try the function below (updated to work for React <16 and 16+):

window.FindReact = function(dom) {
    let key = Object.keys(dom).find(key=>key.startsWith("__reactInternalInstance$"));
    let internalInstance = dom[key];
    if (internalInstance == null) return null;

    if (internalInstance.return) { // react 16+
        return internalInstance._debugOwner
            ? internalInstance._debugOwner.stateNode
            : internalInstance.return.stateNode;
    } else { // react <16
        return internalInstance._currentElement._owner._instance;
    }
}

Usage:

var someElement = document.getElementById("someElement");
FindReact(someElement).setState({test1: test2});


来源:https://stackoverflow.com/questions/47166101/is-it-possible-to-retrieve-a-components-instance-from-a-react-fiber

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!