[英]Ref error in React.JS Ref - createRef, useRef, and using Refs
I am trying to use the ref
property using React.我正在尝试使用 React 使用
ref
属性。 I get a strange error in my browser, and I am not able to figure out what the problem is.我的浏览器出现一个奇怪的错误,我无法弄清楚问题是什么。 Can anyone explain to me why I get this error:
任何人都可以向我解释为什么我会收到此错误:
Error: Invariant Violation: addComponentAsRefTo(...): Only a ReactOwner can have refs.
错误:不变违规:addComponentAsRefTo(...):只有 ReactOwner 可以有 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).这通常意味着您尝试向没有所有者的组件添加 ref(即,不是在另一个组件的
render
方法中创建的)。 Try rendering this component inside of a new top-level component which will hold the ref.尝试在一个新的顶级组件中渲染这个组件,该组件将保存 ref。
when I have this code:当我有这个代码时:
/**
* @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
);
}());
Your code is correct.你的代码是正确的。
Working jsFiddle: http://jsfiddle.net/reactjs/69z2wepo/工作 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
);
According to the error message, you're placing a ref on an un-owned element, but in the code you provided the h1
is owned by the App
.根据错误消息,您将 ref 放置在未拥有的元素上,但在您提供的代码中,
h1
归App
。 Is your code different from what you pasted above?您的代码与上面粘贴的代码不同吗?
Note ( 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.
This answer may help you visit , check out your code carefully to aim at these two questions, my error is caused by the latter one.这个答案可以帮助您访问,仔细检查您的代码以针对这两个问题,我的错误是由后一个引起的。
In my code, I've written require("React") require("React-dom")
, actually it is require('react')
, I modified my code, it worked.在我的代码中,我写了
require("React") require("React-dom")
,实际上它是require('react')
,我修改了我的代码,它起作用了。 All the errors are caused by the two factors.所有的错误都是由这两个因素造成的。 Just check your code completely.
只需完全检查您的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.