What does 'Only a ReactOwner can have refs.' mean?

前端 未结 12 2508
时光说笑
时光说笑 2020-11-27 15:50

I have a simple react component with a form in it:

var AddAppts = React.createClass({
    handleClick:          


        
相关标签:
12条回答
  • 2020-11-27 16:11

    For me the reason for the same problem was that I've imported the ReactDom globally, as a property of the window object, like this:

    import ReactDOM from 'react-dom'
    window.ReactDOM = ReactDOM
    

    removing window.ReactDOM = ReactDOM fixed the problem.

    0 讨论(0)
  • 2020-11-27 16:15

    This is FYI for people using react and redux-devtools who are getting OP's message. Your structure looks like

    project
      client
      node_modules
        react
        redux-devtools
          node_modules
            react
    

    The code in client will require the first react module; that in redux-devtools will require the other react. The react module keeps state and assumes it has all the state.

    You get the OP's message because your state is split between the 2 react modules. This situation is what I believe @asbjornenge refers to.

    I was bundling the client code with webpack, so I used that to handle the issue. You can force all require and import to always use the first react by adding the following to webpack.config.js

    module.exports = {
      ...
      resolve: {
        alias: {
          'react': path.join(__dirname, 'node_modules', 'react')
        },
        extensions: ['', '.js']
      },
      ...
    );
    

    I have not looked into what I would need to do if the situation occurred with unbundled code running on node.

    0 讨论(0)
  • 2020-11-27 16:19

    Just in case. Be aware of the React module name you are using (it is case-sensitive). I've got the same error when by coincidence I tried to require React dependency with different names in two separate modules.

    //module1.js
    var React = require('react');
    ...
    
    //module2.js
    var React = require('React');
    ....
    

    It works and even renders something but the Only a ReactOwner can have refs... error appears.

    0 讨论(0)
  • 2020-11-27 16:23

    I saw this error while developing a react module that was linked to a test project using npm link. Switching to a regular dependency solved the problem.

    It seems that React doesn't like npm link.

    0 讨论(0)
  • 2020-11-27 16:23

    There is another situation.

    I set the React as external library in the webpack.config.js and import react.js from cdnjs.

    externals: {
      'react': 'React'
    }
    

    When I using an ui library depend on React,such as material-ui,react-bootstrap,this issue occurred.

    0 讨论(0)
  • 2020-11-27 16:23

    Instead of

    <input ref="title"></input>
    

    Try this

    <input ref={(title) => this.title = title}></input>
    
    0 讨论(0)
提交回复
热议问题