基于useImperativeHandle的使用解析
useImperativeHandle的使用
你不能在函數(shù)組件上使用 ref 屬性,因?yàn)樗鼈儧](méi)有實(shí)例:
import React, { Component } from 'react'; function MyFunctionComponent() { ? return <input /> } class Parent extends React.Component { ? constructor(props) { ? ? super(props); ? ? this.textInput = React.createRef(); ? } ? render() { ? ? return ( ? ? ? <MyFunctionComponent ref={this.textInput} /> ? ? ); ? } }
如果你需要使用 ref,你應(yīng)該將組件轉(zhuǎn)化為一個(gè) class,就像當(dāng)你需要使用生命周期鉤子或 state 時(shí)一樣。
不管怎樣,你可以在函數(shù)組件內(nèi)部使用 ref 屬性,只要它指向一個(gè) DOM 元素或 class 組件:
function CustomTextInput(props) { ? // 這里必須聲明 textInput,這樣 ref 才可以引用它 ? let textInput = React.createRef(); ? function handleClick() { ? ? textInput.current.focus(); ? } ? return ( ? ? <div> ? ? ? <input ? ? ? ? type="text" ? ? ? ? ref={textInput} /> ? ? ? <input ? ? ? ? type="button" ? ? ? ? value="Focus the text input" ? ? ? ? onClick={handleClick} ? ? ? /> ? ? </div> ? ); }
在下面的示例中,MyFunctionComponent 使用 React.forwardRef 來(lái)獲取傳遞給它的 ref,然后轉(zhuǎn)發(fā)到它渲染的 DOM button:
const MyFunctionComponent = React.forwardRef((props, ref) => ( ? <button ref={ref}> ? ? {props.children} ? </button> )) class Parent extends React.Component { ? constructor(props) { ? ? super(props); ? ? this.textInput = React.createRef(); ? } ? componentDidMount() { ? ? console.log(this.textInput.current) ? } ? render() { ? ? return ( ? ? ? <MyFunctionComponent ref={this.textInput} /> ? ? ); ? } }
第二個(gè)參數(shù) ref 只在使用 React.forwardRef 定義組件時(shí)存在。常規(guī)函數(shù)和 class 組件不接收 ref 參數(shù),且 props 中也不存在 ref。
useImperativeHandle
useImperativeHandle 可以讓你在使用 ref 時(shí)自定義暴露給父組件的實(shí)例值。useImperativeHandle 應(yīng)當(dāng)與 forwardRef 一起使用:
const MyFunctionComponent = React.forwardRef((props, ref) => { const inputRef = useRef(); useImperativeHandle(ref, () => ({ focus: () => { inputRef.current.focus(); } })); return ( <input ref={inputRef} /> ) }) class Parent extends React.Component { constructor(props) { super(props); this.textInput = React.createRef(); } componentDidMount() { this.textInput.current.focus() } render() { return ( <MyFunctionComponent ref={this.textInput} /> ); } }
使用useImperativeHandle時(shí)父組件第一次沒(méi)拿到子組件方法
背景需求
一個(gè)tab兩個(gè)按鈕A、B,默認(rèn)選中的A,當(dāng)點(diǎn)擊到B時(shí)需要顯示B對(duì)應(yīng)的圖表??紤]到B的圖表在頁(yè)面加載時(shí)已經(jīng)初始化完成,所以點(diǎn)擊B時(shí)再調(diào)用圖表的resize方法。由于tab中的圖表是寫(xiě)在子組件里,所以通過(guò)useImperativeHandle實(shí)現(xiàn)父組件調(diào)用子組件方法,React版本"react": "^18.1.0",代碼如下
父組件:
const childRef = useRef() const item = [{ ? ? ? ? name: 'XXXX', ? ? ? ? content: <RunningRecord cRef={childRef} />, ? ? ? ? handClick: childRef.current?.resizeChart }] return <> ? ? …… ? ? <li onClick={() => { ? ? ? ? ? ? setTimeout(() => { ? ? ? ? ? ? ? ? console.log('~~item.handClick',item.handClick) ? ? ? ? ? ? ? ? item.handClick?.() ? ? ? ? ? ? }, 200) ? ? ? ? }} ? ? ? ? key={item.name}> ? ? ? ? {item.name} ? ? </li> ? ? …… ? ? <RunningRecord cRef={childRef} /> </>
子組件:
function RunningRecord({ cRef }) { ? ? …… ? ? useImperativeHandle(cRef,()=>({ ? ? ? ? resizeChart:()=> {dosomething……} ? ? }))
問(wèn)題
這樣寫(xiě)在本地開(kāi)發(fā)模式中正常運(yùn)行,但生產(chǎn)環(huán)境中父組件首次加載不能拿到子組件的方法,需tab切換到A再次且到B才行。猜想原因,大概在生產(chǎn)環(huán)境中,父組件把子組件暴露出來(lái)的方法綁定到UI中的點(diǎn)擊事件中,而子組件初始化的時(shí)機(jī)晚,初始完成后并沒(méi)有把事件傳回來(lái)。
這個(gè)猜想不一定準(zhǔn)確,歡迎知道的小伙伴們補(bǔ)充。
解決方法
在父組件中,將子組件賦值的過(guò)程放在useEffect中,不寫(xiě)依賴項(xiàng)參數(shù)(不是沒(méi)有依賴的空數(shù)組),再運(yùn)行,一切正常。
const usageRecordData = [{ ? ? name: 'XXXX', ? ? content: <RunningRecord cRef={childRef} />, }] useEffect(() => { ? ? usageRecordData[1].handClick = childRef.current?.resizeChart })
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
react 實(shí)現(xiàn)頁(yè)面代碼分割、按需加載的方法
本篇文章主要介紹了react 實(shí)現(xiàn)頁(yè)面代碼分割、按需加載的方法,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-04-04react navigation中點(diǎn)擊底部tab怎么傳遞參數(shù)
本文主要介紹了react navigation中點(diǎn)擊底部tab怎么傳遞參數(shù),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-04-04React Navigation 使用中遇到的問(wèn)題小結(jié)
本篇文章主要介紹了React Navigation 使用中遇到的問(wèn)題小結(jié),主要是安卓和iOS中相對(duì)不協(xié)調(diào)的地方,特此記錄,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-05-05關(guān)于react hook useState連續(xù)更新對(duì)象的問(wèn)題
這篇文章主要介紹了關(guān)于react hook useState連續(xù)更新對(duì)象的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-03-03react中監(jiān)聽(tīng)props的改變方式
這篇文章主要介紹了react中監(jiān)聽(tīng)props的改變方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-01-01解決React報(bào)錯(cuò)Style prop value must be a
這篇文章主要為大家介紹了React報(bào)錯(cuò)Style prop value must be an object解決,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-12-12每天一個(gè)hooks學(xué)習(xí)之useUnmount
這篇文章主要為大家介紹了每天一個(gè)hooks學(xué)習(xí)之useUnmount,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-05-05