Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
550 views
in Technique[技术] by (71.8m points)

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

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

var AddAppts = React.createClass({
    handleClick: function() {
        var title = this.refs.title.getDOMNode().value;
        ....

        var appt = {
            heading: title
            ...
        }

        CalendarActions.addAppointment(appt);
    },

    render: function() {
        return (
            <div>
                <label>Description</label>
                <input ref="title"></input>
                ...
            </div>
        );
    }
});
module.exports = AddAppts;

I am trying to render this component in another react component:

  var AddAppt = require('./AddAppts');

  render: function() {
    return (
      <div>
        <AddAppt />
      </div>
    );
  }

but I get this error:

 Uncaught Error: Invariant Violation: addComponentAsRefTo(...): Only a ReactOwner can have refs. This usually means that you're trying to add a ref to a component that doesn't have an owner (that is, was not created inside of another component's `render` method). Try rendering this component inside of a new top-level component which will hold the ref.

I have googled it, but cannot figure out what I need to do to fix this issue.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...