本篇内容主要讲解“React报错解决之ref返回undefined或null怎么解决”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“React报错解决之ref返回undefined或null怎么解决”吧!
当我们试图在其对应的DOM元素被渲染之前访问其current
属性时,React的ref通常会返回undefined
或者null
。为了解决该问题,可以在useEffect
钩子中访问ref
,或者当事件触发时再访问ref
。
import {useRef, useEffect} from 'react';
export default function App() {
const ref = useRef();
console.log(ref.current); // ????️ undefined here
useEffect(() => {
const el2 = ref.current;
console.log(el2); // ????️ element here
}, []);
return (
<div>
<div ref={ref}>
<h3>Hello</h3>
</div>
</div>
);
}
useRef()
钩子可以传递一个初始值作为参数。该钩子返回一个可变的ref
对象,ref
对象上的current
属性被初始化为传递的参数。
我们没有为useRef
传递初始值,因此其current
属性设置为undefined
。如果我们将null
传递给钩子,如果立即访问其current
属性,将会得到null
。
需要注意的是,我们必须访问
ref
对象上的current
属性,以此来访问设置了ref
属性的div
元素。
当我们为元素传递ref
属性时,比如说,<div ref={myRef} />
,React将ref
对象的.current
属性设置为相应的DOM节点。
我们使用useEffect
钩子,是因为我们想要确保ref
已经设置在元素上,并且元素已经渲染到DOM上。
如果我们尝试在组件中直接访问ref
上的current
属性,我们会得到undefined,是因为 ref
还没有被设置,而且 div
元素还没有被渲染。
你也可以在事件处理函数中访问ref
的current
属性。
import {useRef, useEffect} from 'react';
export default function App() {
const ref = useRef();
console.log(ref.current); // ????️ undefined here
useEffect(() => {
const el2 = ref.current;
console.log(el2); // ????️ element here
}, []);
const handleClick = () => {
console.log(ref.current); // ????️ element here
};
return (
<div>
<div ref={ref}>
<h3>Hello</h3>
</div>
<button onClick={handleClick}>Click</button>
</div>
);
}
当用户点击按钮的时候,ref
已经被设置好了,相应的元素已经被渲染到DOM中,所以我们能够访问它。
可以在useEffect
钩子中访问ref
,或者当事件触发时再访问ref
。也就是说,要确保元素已经渲染到DOM上。
到此这篇关于React报错解决之ref返回undefined或null的文章就介绍到这了,更多相关React ref返回undefined null内容请搜索亿速云以前的文章或继续浏览下面的相关文章希望大家以后多多支持亿速云!
附:ref的值根据节点的类型而有所不同
当在refHTML元素上使用该属性时,ref在构造函数中创建的属性将React.createRef()接收底层DOM元素作为其current属性。
在ref自定义类组件上使用该属性时,该ref对象将接收组件的已安装实例作为其current。
您可能无法ref在函数组件上使用该属性,因为它们没有实例。
class CustomTextInput extends React.Component {
constructor(props) {
super(props);
// create a ref to store the textInput DOM element
this.textInput = React.createRef();
this.focusTextInput = this.focusTextInput.bind(this);
}
focusTextInput() {
// Explicitly focus the text input using the raw DOM API
// Note: we're accessing "current" to get the DOM node
this.textInput.current.focus();
}
render() {
// tell React that we want to associate the <input> ref
// with the `textInput` that we created in the constructor
return (
<div>
<input
type="text"
ref={this.textInput} />
<input
type="button"
value="Focus the text input"
onClick={this.focusTextInput}
/>
</div>
);
}
}
current当组件安装时,React将为该属性分配DOM元素,并null在卸载时将其分配回。ref更新发生之前componentDidMount或componentDidUpdate生命周期方法。
到此,相信大家对“React报错解决之ref返回undefined或null怎么解决”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。