iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 24
0
Modern Web

React.js 從 【0】 到【1】推坑計畫 系列 第 24

【Day 24】 useRef

useRef 是一個可以讓我們抓取到 DOM 節點的 hooks。

實作上非常簡單,直接來看範例吧:

import React, { useRef } from 'react'

const UseRefExample = () => {
	const inputRef = useRef(null);

	const handleClick = () => {
		inputRef.current.focus();
	}
	return (
		<div>
			<input ref={inputRef} placeholder="it邦幫忙"/>
			<button onClick={handleClick}>click me</button>
		</div>
	)
}


export default UseRefExample;

要使用 useRef 首先必須先從 react 引入它

接著

const inputRef = useRef(null);

呼叫 useRef 建立出一個物件實體,null 表示初始值設定為 null。

<input ref={inputRef} placeholder="it邦幫忙"/>

將建立的物件丟入我們要抓取的 DOM 元素的 ref attribute 中,做完這件事可以想成我們對這個 input 有了控制權。

要對現在綁定的 DOM node 做操作需要到.current properity 中。
原因是剛剛說 useRef 回傳的是一個物件,**{current: ...}**長得大概是這個樣字。

const handleClick = () => {
	inputRef.current.focus();
}

因此就完成點擊按鈕後 input 會被 focus 的功能。

有了 useRef 就可以做到例如頁面刷新後自動 foucs 在某個欄位,或是某欄位送出後自動 focus 到下一個欄位等對 DOM 的操作。

最後看一下官方給我們的提示:

Keep in mind that useRef doesn’t notify you when its content changes. Mutating the .current property doesn’t cause a re-render. If you want to run some code when React attaches or detaches a ref to a DOM node, you may want to use a callback ref instead.

重點在於改變 current 的值不會觸發 re-render,就交給讀者自行探究囉!


上一篇
【Day 23】useMemo
下一篇
【Day 25】useCallback - 學會把函式記起來
系列文
React.js 從 【0】 到【1】推坑計畫 30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言