hooks之useRef

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è)面渲染的變量
等等

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容