是否可以从React Fiber检索组件的实例?

时间:2017-11-07 19:35:09

标签: reactjs react-fiber

在React的v16之前 - 也就是说,在引入React光纤之前 - 可以采用DOM元素并检索React组件实例,如下所示:

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;
};

这不再适用于使用新光纤实施的React v16。具体来说,上面的代码在行const comparWrapper = compInternals._owner处引发错误,因为不再有_owner属性。因此,您也无法访问_instance

我的问题是如何在v16的光纤实现中从DOM元素中检索实例?

1 个答案:

答案 0 :(得分:0)

您可以尝试使用以下功能(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;
    }
}

用法:

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