React報錯解決之ref返回undefined或null
總覽
當我們試圖在其對應的DOM元素被渲染之前訪問其current屬性時,React的ref通常會返回undefined或者null。為了解決該問題,可以在useEffect鉤子中訪問ref,或者當事件觸發(fā)時再訪問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}>
<h2>Hello</h2>
</div>
</div>
);
}useEffect
useRef()鉤子可以傳遞一個初始值作為參數(shù)。該鉤子返回一個可變的ref對象,ref對象上的current屬性被初始化為傳遞的參數(shù)。
我們沒有為useRef傳遞初始值,因此其current屬性設置為undefined。如果我們將null傳遞給鉤子,如果立即訪問其current屬性,將會得到null。
需要注意的是,我們必須訪問
ref對象上的current屬性,以此來訪問設置了ref屬性的div元素。
當我們?yōu)樵貍鬟fref屬性時,比如說,<div ref={myRef} /> ,React將ref對象的.current屬性設置為相應的DOM節(jié)點。
我們使用useEffect鉤子,是因為我們想要確保ref已經(jīng)設置在元素上,并且元素已經(jīng)渲染到DOM上。
如果我們嘗試在組件中直接訪問ref上的current屬性,我們會得到undefined,是因為 ref 還沒有被設置,而且 div 元素還沒有被渲染。
事件
你也可以在事件處理函數(shù)中訪問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}>
<h2>Hello</h2>
</div>
<button onClick={handleClick}>Click</button>
</div>
);
}當用戶點擊按鈕的時候,ref已經(jīng)被設置好了,相應的元素已經(jīng)被渲染到DOM中,所以我們能夠訪問它。
總結(jié)
可以在useEffect鉤子中訪問ref,或者當事件觸發(fā)時再訪問ref。也就是說,要確保元素已經(jīng)渲染到DOM上。
到此這篇關于React報錯解決之ref返回undefined或null的文章就介紹到這了,更多相關React ref返回undefined null內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
附:ref的值根據(jù)節(jié)點的類型而有所不同
- 當在refHTML元素上使用該屬性時,ref在構(gòu)造函數(shù)中創(chuàng)建的屬性將React.createRef()接收底層DOM元素作為其current屬性。
- 在ref自定義類組件上使用該屬性時,該ref對象將接收組件的已安裝實例作為其current。
您可能無法ref在函數(shù)組件上使用該屬性,因為它們沒有實例。
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更新發(fā)生之前componentDidMount或componentDidUpdate生命周期方法。

