gpt4 book ai didi

reactjs - React.JS Ref 中的 Ref 错误 - createRef、useRef 和 using Refs

转载 作者:行者123 更新时间:2023-12-03 13:27:59 28 4
gpt4 key购买 nike

我正在尝试通过 React 使用 ref 属性。我的浏览器出现奇怪的错误,但我无法弄清楚问题出在哪里。谁能向我解释一下为什么我会收到此错误:

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.

当我有这个代码时:

/**
* @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
);
}());

最佳答案

您的代码是正确的。

工作中的 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.

关于reactjs - React.JS Ref 中的 Ref 错误 - createRef、useRef 和 using Refs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27267219/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com