reactjs object doesn't have key __reactInterna

2019-08-02 03:04发布

问题:

I copied this function from another stackoverflow subject (to call child methods outside render) and it worked in a small test project

window.FindReact = function(dom) {
  for (var key in dom) {
    if (key.startsWith("__reactInternalInstance$")) {
        var compInternals = dom[key]._currentElement;
        var compWrapper = compInternals._owner;
        var comp = compWrapper._instance;
        return comp;
    }
  }
  return null;
};

I made a class that shows a messagebox in mid of screen (Fade-in; show msg few seconds; then fade out)

and I could call the method to show the message of the child component directly thanks to above function. So all good.

Then I copied that object (messagebox) to my main project and copied above function to the parent object. And when I call it, no key ... well not the key I'm looking for

i listed the keys both of the working and failing project. all keys are the same except the first one (which is missing in the fail project)

key=__reactInternalInstance$bv23g7yipka

The fail project works, no errors, also the message component works (can call from inside to show message)

I really have no idea why this fails (key is missing), hope some of you do.

回答1:

i checked the package.js and noticed the different versions of all modules. So updated them (react/react-dom/webpack/babel-loader) and then it worked :)