React報錯解決之ref返回undefined或null
總覽
當我們試圖在其對應(yīng)的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
屬性設(shè)置為undefined
。如果我們將null
傳遞給鉤子,如果立即訪問其current
屬性,將會得到null
。
需要注意的是,我們必須訪問
ref
對象上的current
屬性,以此來訪問設(shè)置了ref
屬性的div
元素。
當我們?yōu)樵貍鬟fref
屬性時,比如說,<div ref={myRef} />
,React將ref
對象的.current
屬性設(shè)置為相應(yīng)的DOM節(jié)點。
我們使用useEffect
鉤子,是因為我們想要確保ref
已經(jīng)設(shè)置在元素上,并且元素已經(jīng)渲染到DOM上。
如果我們嘗試在組件中直接訪問ref
上的current
屬性,我們會得到undefined,是因為 ref
還沒有被設(shè)置,而且 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)被設(shè)置好了,相應(yīng)的元素已經(jīng)被渲染到DOM中,所以我們能夠訪問它。
總結(jié)
可以在useEffect
鉤子中訪問ref
,或者當事件觸發(fā)時再訪問ref
。也就是說,要確保元素已經(jīng)渲染到DOM上。
到此這篇關(guān)于React報錯解決之ref返回undefined或null的文章就介紹到這了,更多相關(guān)React ref返回undefined null內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
附: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生命周期方法。
相關(guān)文章
一起來學(xué)習(xí)React元素的創(chuàng)建和渲染
這篇文章主要為大家詳細介紹了React元素的創(chuàng)建和渲染,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助2022-03-03react學(xué)習(xí)筆記之state以及setState的使用
這篇文章主要介紹了react學(xué)習(xí)筆記之state以及setState的使用,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-12-12