react hooks已經(jīng)是大勢(shì)所趨,簡(jiǎn)單整理一下useRef的使用:
useRef基礎(chǔ)
1、useRef返回一個(gè)可變的 ref 對(duì)象,該對(duì)象只有個(gè) current 屬性,初始值為傳入的參數(shù)( initialValue )。
2、返回的 ref 對(duì)象在組件的整個(gè)生命周期內(nèi)保持不變,每次返回同一個(gè)引用
3、當(dāng)更新 current 值時(shí)并不會(huì)引起頁(yè)面重新渲染
4、更新 useRef 是 side effect (副作用),所以一般寫(xiě)在 useEffect 或 event 里
5、useRef 類(lèi)似于類(lèi)組件的 this
const domRef = useRef(initialValue)
為什么用useRef
頁(yè)面不需要重新渲染,就可以取到最新的值
如何優(yōu)雅獲取子組件
通過(guò)useImperativeHandle,配合forwardRef
import React, {
MutableRefObject,
useState,
useImperativeHandle,
useRef,
forwardRef,
useCallback
} from 'react'
interface IProps {
label: string
}
let ChildInput = forwardRef((props: IProps, ref: any) => {
const { label } = props
const [value, setValue] = useState('')
// 作用: 減少父組件獲取的DOM元素屬性,只暴露給父組件需要用到的DOM方法
// 參數(shù)1: 父組件傳遞的ref屬性
// 參數(shù)2: 返回一個(gè)對(duì)象,父組件通過(guò)ref.current調(diào)用對(duì)象中方法
useImperativeHandle(ref, () => ({
getValue
}))
const handleChange = (e: any) => {
const value = e.target.value
setValue(value)
}
const getValue = useCallback(() => {
return value
}, [value])
return (
<div>
<span>{label}:</span>
<input type="text" value={value} onChange={handleChange} />
</div>
)
})
const ParentCom: React.FC = (props: any) => {
const childRef: MutableRefObject<any> = useRef({})
const handleFocus = () => {
const node = childRef.current
console.log(node.getValue())
}
return (
<div>
<ChildInput label={'名稱(chēng)'} ref={childRef} />
<button onClick={handleFocus}>focus</button>
</div>
)
}
export default ParentCom
常用使用場(chǎng)景
定時(shí)器
獲取Dom元素
定義不需要引起頁(yè)面渲染的變量
等等