参考错误React

时间:2014-12-03 08:49:39

标签: reactjs react-jsx

我正在尝试使用React使用ref属性。我的浏览器出现了一个奇怪的错误,我无法弄清问题是什么。 任何人都可以向我解释为什么我会收到此错误:

  

错误:不变违规:addComponentAsRefTo(...):只有ReactOwner可以有refs。这通常意味着您尝试将ref添加到没有所有者的组件(即,未在另一个组件的render方法内创建)。尝试在新的顶级组件中渲染此组件,该组件将保存参考。

当我有这段代码时:

/**
* @jsx React.DOM
*/
(function(){
var react = require('react');


var App = react.createClass({

    render: function() {
        return (
            <h1 ref="myRef">This is a test</h1>
        );
    }

});

react.render(
    <App />,
    document.body
);
}());

2 个答案:

答案 0 :(得分:0)

您的代码是正确的。

工作jsFiddle:http://jsfiddle.net/reactjs/69z2wepo/

var App = React.createClass({

    render: function() {
        return (
            <h1 ref="myRef">This is a test</h1>
        );
    }

});

React.render(
    <App />,
    document.body
);

根据错误消息,您要在非自有元素上放置引用,但在您提供的代码中,h1App所有。你的代码与你上面的代码有什么不同吗?

注意(from the docs):

In React, an owner is the component that sets the props of other components ... 
It's important to draw a distinction between the owner-ownee relationship and the parent-child relationship. 

答案 1 :(得分:0)

这个答案可以帮助你visit,仔细检查你的代码以针对这两个问题,我的错误是由后者引起的。
在我的代码中,我写了require("React") require("React-dom"),实际上它是require('react'),我修改了我的代码,它运行了。所有错误都是由两个因素引起的。只需完整检查您的代码。