自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

React ref 從原理到應(yīng)用

開發(fā) 前端
Fiber是React更新時的最小單元,是一種包含指針的數(shù)據(jù)結(jié)構(gòu),從數(shù)據(jù)結(jié)構(gòu)上看Fiber架構(gòu) ≈ 樹 + 鏈表。Fiber單元是從 jsx createElement之后根據(jù)ReactElement生成的,相比 ReactElement,F(xiàn)iber單元具備動態(tài)工作能力。

[[398682]]

提到 ref或者 refs 如果你用過React 16以前的版本 第一印象都是用來訪問DOM或者修改組件實(shí)例的,

正如官網(wǎng)所介紹的這樣:

 

然后到了React 16.3出現(xiàn)的 createRef 以及16.8 hooks中的 useRef出現(xiàn)時,發(fā)現(xiàn)這里的ref好像不僅僅只有之前的綁定到DOM/組件實(shí)例的 作用?本文將帶你逐一梳理這些知識點(diǎn),并嘗試分析相關(guān)源碼。

前置知識

這部分知識點(diǎn)不是本文重點(diǎn),每個點(diǎn)展開都非常龐大,了方便本文理解先在這里簡單提及。

Fiber架構(gòu)

Fiber是React更新時的最小單元,是一種包含指針的數(shù)據(jù)結(jié)構(gòu),從數(shù)據(jù)結(jié)構(gòu)上看Fiber架構(gòu) ≈ 樹 + 鏈表。

Fiber單元是從 jsx createElement之后根據(jù)ReactElement生成的,相比 ReactElement,F(xiàn)iber單元具備動態(tài)工作能力。

React 的工作流程

使用chrome perfomance錄制一個react應(yīng)用渲染看函數(shù)調(diào)用棧會看到下面這張圖

這三塊內(nèi)容分別代表: 1.生成react root節(jié)點(diǎn) 2.reconciler 協(xié)調(diào)生成需要更新的子節(jié)點(diǎn) 3.將節(jié)點(diǎn)更新commit 到視圖

Hooks基礎(chǔ)知識

在函數(shù)組件中每執(zhí)行一次use開頭的hook函數(shù)都會生成一個hook對象。

  1. type Hook = { 
  2.   memoizedState: any,   // 上次更新之后的最終狀態(tài)值 
  3.   queue: UpdateQueue, //更新隊列 
  4.   next, // 下一個 hook 對象 
  5. }; 

其中memoizedState會保存該hook上次更新之后的最終狀態(tài),比如當(dāng)我們使用一次useState之后就會在memoizedState中保存初始值。

React 中大部分 hook 分為兩個階段:第一次初始化時`mount`階段和更新`update`時階段

hooks函數(shù)的執(zhí)行分兩個階段 mount和 update,比如 useState只會在初始化時執(zhí)行一次,下文中將提到的

useImperativeHandle 和 useRef也包括在內(nèi)。

調(diào)試源碼

本文已梳理摘取了源碼相關(guān)的函數(shù),但你如果配合源碼調(diào)試一起食用效果會更加。

本文基于React v17.0.2。

拉取React代碼并安裝依賴

將react,scheduler以及react-dom打包為commonjs

yarn build react/index,react-dom/index,scheduler --type NODE

3.進(jìn)入build/node_modules/react/cjs 執(zhí)行yarn link 同理 react-dom

4.在 build/node_modules/react/cjs/react.development.js中加入link標(biāo)記console以確保檢查link狀態(tài)

5.使用create-react-app創(chuàng)建一個測試應(yīng)用 并link react,react-dom

ref prop

組件上的ref屬性是一個保留屬性,你不能把ref當(dāng)成一個普通的prop屬性在一個組件中獲取,比如:

  1. const Parent = () => { 
  2.     return <Child ref={{test:1}}> 
  3. const Child = (props) => { 
  4.   console.log(props); 
  5.   // 這里獲取不到ref屬性 
  6.     return <div></div> 

 這個ref去哪里了呢, React本身又對它做了什么呢?

我們知道React的解析是從createElement開始的,找到了下面創(chuàng)建ReactElement的地方,確實(shí)有對ref保留屬性的處理。

  1. export function createElement(type, config, children) { 
  2. let propName; 
  3.   // Reserved names are extracted 
  4.   const props = {}; 
  5.   let ref = null
  6.   if (config != null) { 
  7.     if (hasValidRef(config)) { 
  8.       ref = config.ref; 
  9.     } 
  10.     for (propName in config) { 
  11.       if ( 
  12.         hasOwnProperty.call(config, propName) && 
  13.         !RESERVED_PROPS.hasOwnProperty(propName) 
  14.       ) { 
  15.         props[propName] = config[propName]; 
  16.       } 
  17.     } 
  18.   } 
  19.   return ReactElement( 
  20.     type, 
  21.     key
  22.     ref, 
  23.     props, 
  24.     ... 
  25.   ); 

從createElement開始就已經(jīng)創(chuàng)建了對ref屬性的引用。

createElement之后我們需要構(gòu)建Fiber工作樹,接下來主要講對ref相關(guān)的處理。

React對于不同的組件有不通的處理

先主要關(guān)注 FunctionComponent/ClassComponent/HostComponent(原生html標(biāo)簽)

FunctionComponent

  1. function updateFunctionComponent(current, workInProgress, Component, nextProps, renderLanes) { 
  2.       try { 
  3.         nextChildren = renderWithHooks(current, workInProgress, Component, nextProps, context, renderLanes); 
  4.       } finally { 
  5.         reenableLogs(); 
  6.       } 
  7.       reconcileChildren(current, workInProgress, nextChildren, renderLanes); 
  8.       return workInProgress.child; 
  9. functin renderWithHooks(current, workInProgress, Component, props, secondArg, nextRenderLanes){ 
  10.             children = Component(props, secondArg); // 這里的Component就是指我們的函數(shù)組件 
  11.                 return children; 

我們可以看到函數(shù)組件在渲染的時候就是直接執(zhí)行。

Class組件和原生標(biāo)簽的ref prop

ClassComponent

  1. function updateClassComponent(current, workInProgress, Component, nextProps, renderLanes) { 
  2.   ... 
  3.   { 
  4.     ... 
  5.     constructClassInstance(workInProgress, Component, nextProps); 
  6.         .... 
  7.   } 
  8.   var nextUnitOfWork = finishClassComponent(current, workInProgress, Component, shouldUpdate, hasContext, renderLanes); 
  9.     ... 
  10.   return nextUnitOfWork; 
  11. function constructClassInstance(workInProgress, ctor, props) { 
  12.     .... 
  13.   var instance = new ctor(props, context); 
  14.   // 把instance實(shí)例掛載到workInProgress stateNode屬性上 
  15.   adoptClassInstance(workInProgress, instance); 
  16.     ..... 
  17.   return instance; 
  18. function finishClassComponent(current, workInProgress, Component, shouldUpdate, hasContext, renderLanes) { 
  19.   // 標(biāo)記是否有ref更新 
  20.   markRef(current, workInProgress); 
  21. function markRef(current, workInProgress) { 
  22.   var ref = workInProgress.ref; 
  23.   if (current === null && ref !== null || current !== null && current.ref !== ref) { 
  24.     // Schedule a Ref effect 
  25.     workInProgress.flags |= Ref; 
  26.   } 

ClassComponent則是通過構(gòu)造函數(shù)生成實(shí)例并標(biāo)記了ref屬性。

回顧一下之前提到的React工作流程,既然是要將組件實(shí)例或者真實(shí)DOM賦值給ref那肯定不能在一開始就處理這個ref,而是根據(jù)標(biāo)記到commit階段再給ref賦值。

  1. function commitLayoutEffectOnFiber(finishedRoot, current, finishedWork, committedLanes) { 
  2.     .... 
  3.   { 
  4.     if (finishedWork.flags & Ref) { 
  5.       commitAttachRef(finishedWork); 
  6.     } 
  7.   } 
  8.   .... 
  9. function commitAttachRef(finishedWork) { 
  10.   var ref = finishedWork.ref; 
  11.   if (ref !== null) { 
  12.     var instance = finishedWork.stateNode; 
  13.     var instanceToUse; 
  14.     switch (finishedWork.tag) { 
  15.       case HostComponent: 
  16.         // getPublicInstance 這里調(diào)用了DOM API 返回了DOM對象 
  17.         instanceToUse = getPublicInstance(instance); 
  18.         break; 
  19.       default
  20.         instanceToUse = instance; 
  21.     }  
  22.     // 對函數(shù)回調(diào)形式設(shè)置ref的處理 
  23.     if (typeof ref === 'function') { 
  24.       { 
  25.         ref(instanceToUse); 
  26.       } 
  27.     } else { 
  28.       ref.current = instanceToUse; 
  29.     } 
  30.   } 

在commit階段,如果是原生標(biāo)簽則將真實(shí)DOM賦值給ref對象的current屬性, 如果是class componnet 則是組件instance。

函數(shù)組件的ref prop

如果你對function組件未做處理直接加上ref,react會直接忽略并在開發(fā)環(huán)境給出警告

函數(shù)組件沒有實(shí)例可以賦值給ref對象,而且組件上的ref prop會被當(dāng)作保留屬性無法在組件中獲取,那該怎么辦呢?

forwardRef

React提供了一個forwardRef函數(shù) 來處理函數(shù)組件的 ref prop,用起來就像下面這個示例:

  1. const Parent = () => { 
  2.     const childRef = useRef(null
  3.   return <Child ref={childRef}/> 
  4. const Child = forWardRef((props,ref) => { 
  5.     return <div>Child</div> 
  6. }} 

 這個方法的源碼主體也非常簡單,返回了一個新的elementType對象,這個對象的render屬性包含了原本的這個函數(shù)組件,而$$typeof則標(biāo)記了這個特殊組件類型。

  1. function forwardRef(render) { 
  2.   .... 
  3.   var elementType = { 
  4.     $$typeof: REACT_FORWARD_REF_TYPE, 
  5.     render: render 
  6.   } 
  7.   .... 
  8.   return elementType; 
  9.  } 

那么React對forwardRef這個特殊的組件是怎么處理的呢

  1. function beginWork(current, workInProgress, renderLanes) { 
  2.     ... 
  3.   switch (workInProgress.tag) { 
  4.     case FunctionComponent: 
  5.       { 
  6.        ... 
  7.         return updateFunctionComponent(current, workInProgress, _Component, resolvedProps, renderLanes); 
  8.       } 
  9.     case ClassComponent: 
  10.       { 
  11.                 .... 
  12.         return updateClassComponent(current, workInProgress, _Component2, _resolvedProps, renderLanes); 
  13.       } 
  14.     case HostComponent: 
  15.       return updateHostComponent(current, workInProgress, renderLanes); 
  16.     case ForwardRef: 
  17.       { 
  18.                 .... 
  19.         // 第三個參數(shù)type就是forwardRef創(chuàng)建的elementType 
  20.         return updateForwardRef(current, workInProgress, type, _resolvedProps2, renderLanes); 
  21.       } 
  22.    
  23. function updateForwardRef(current, workInProgress, Component, nextProps, renderLanes) { 
  24.     .... 
  25.   var render = Component.render; 
  26.   var ref = workInProgress.ref; // The rest is a fork of updateFunctionComponent 
  27.   var nextChildren; 
  28.   { 
  29.         ... 
  30.     //  將ref引用傳入renderWithHooks 
  31.     nextChildren = renderWithHooks(current, workInProgress, render, nextProps, ref, renderLanes); 
  32.     ... 
  33.   } 
  34.   workInProgress.flags |= PerformedWork; 
  35.   reconcileChildren(current, workInProgress, nextChildren, renderLanes); 
  36.   return workInProgress.child; 

可以看到和上面 FunctionComponent的主要區(qū)別僅僅是把ref保留屬性當(dāng)成普通屬性傳入 renderWithHooks方法!

那么又有一個問題出現(xiàn)了,如果只是傳了一個ref引用,而沒有像Class組件那樣可以attach的實(shí)例,豈不是沒有辦法操作子函數(shù)組件的行為?

用上面的例子驗證一下

  1. const Parent = () => {   
  2.   const childRef = useRef(null
  3.   useEffect(()=>{ 
  4.     console.log(childref) // { current:null } 
  5.   }) 
  6.   return <Child ref={childRef}/> 
  7. const Child = forwardRef((props,ref) => { 
  8.     return <div>Child</div> 
  9. }} 
  10.                           
  11.  const Parent = () => {  
  12.   const childRef = useRef(null
  13.   useEffect(()=>{ 
  14.     console.log(childref) // { current: div } 
  15.   }) 
  16.   return <Child ref={childRef}/> 
  17. const Child = forwardRef((props,ref) => { 
  18.     return <div ref={ref}>Child</div> 
  19. }} 

 結(jié)合輸出可以看出如果單獨(dú)使用forwardRef僅僅只能轉(zhuǎn)發(fā)ref屬性。如果ref最終沒有綁定到一個ClassCompnent或者原生DOM上那么這個ref將不會改變。

假設(shè)一個業(yè)務(wù)場景,你封裝了一個表單組件,想對外暴露一些接口比如說提交的action以及校驗等操作,這樣應(yīng)該如何處理呢?

useImperativeHandle

react為我們提供了這個hook來幫助函數(shù)組件向外部暴露屬性

先看下效果

  1. const Parent = () => {   
  2.   const childRef = useRef(null
  3.   useEffect(()=>{ 
  4.     chilRef.current.sayName();// child 
  5.   }) 
  6.   return <Child ref={childRef}/> 
  7. const Child = forwardRef((props,ref) => { 
  8.   useImperativeHandle(ref,()=>({ 
  9.     sayName:()=>{ 
  10.         console.log('child'
  11.     } 
  12.   })) 
  13.     return <div>Child</div> 
  14. }} 

 看一下該hook的源碼部分(以hook mount階段為例):

  1. useImperativeHandle: function (ref, create, deps) { 
  2.       currentHookNameInDev = 'useImperativeHandle'
  3.       mountHookTypesDev(); 
  4.       checkDepsAreArrayDev(deps); 
  5.       return mountImperativeHandle(ref, create, deps); 
  6.  } 
  7. function mountImperativeHandle(ref, create, deps) { 
  8.   { 
  9.     if (typeof create !== 'function') { 
  10.       error('Expected useImperativeHandle() second argument to be a function ' + 'that creates a handle. Instead received: %s.'create !== null ? typeof create : 'null'); 
  11.     } 
  12.   } // TODO: If deps are provided, should we skip comparing the ref itself? 
  13.   var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null
  14.   var fiberFlags = Update
  15.   return mountEffectImpl(fiberFlags, Layout, imperativeHandleEffect.bind(nullcreate, ref), effectDeps); 
  16. function imperativeHandleEffect(create, ref) { 
  17.   if (typeof ref === 'function') { 
  18.     var refCallback = ref; 
  19.     var _inst = create(); 
  20.     refCallback(_inst); 
  21.     return function () { 
  22.       refCallback(null); 
  23.     }; 
  24.   } else if (ref !== null && ref !== undefined) { 
  25.     var refObject = ref; 
  26.     { 
  27.       if (!refObject.hasOwnProperty('current')) { 
  28.         error('Expected useImperativeHandle() first argument to either be a ' + 'ref callback or React.createRef() object. Instead received: %s.''an object with keys {' + Object.keys(refObject).join(', ') + '}'); 
  29.       } 
  30.     } 
  31.         // 這里執(zhí)行了傳給hook的第二個參數(shù) 
  32.     var _inst2 = create(); 
  33.     refObject.current = _inst2; 
  34.     return function () { 
  35.       refObject.current = null
  36.     }; 
  37.   } 

其實(shí)就是將我們需要暴露的對象及傳給useImperativeHandle的第二個函數(shù)參數(shù)執(zhí)行結(jié)果賦值給了ref的current對象。

同一份引用

到此為止我們大致梳理了組件上ref prop 的工作流程,以及如何在函數(shù)組件中使用ref prop,貌似比想象中簡單。

上面的過程我們注意到從createElement再到構(gòu)建WorkInProgess Fiber樹到最后commit的過程,ref似乎是一直在被傳遞。

中間過程的代碼過于龐大復(fù)雜,但是我們可以通過一個簡單的測試來驗證一下。

  1. const isEqualRefDemo = () => { 
  2.     const isEqualRef = useRef(1) 
  3.   return <input key="test" ref={isEqualRef}> 

對于 class component 和 原生標(biāo)簽來說 就是 createElement 到 commitAttachRef之前:

在createElement里將ref掛載給window對象,然后在commitAttachRef里判斷一下這兩次的ref是否全等。

對于函數(shù)組件來說就是 createElement 到 hook執(zhí)行 imperativeHandleEffect 之前:

  1. const Parent = () => {   
  2.   const childRef = useRef(1) 
  3.   useEffect(()=>{ 
  4.     chilRef.current.sayName();// child 
  5.   }) 
  6.   return <Child ref={childRef}/> 
  7. const Child = forwardRef((props,ref) => { 
  8.   useImperativeHandle(ref,()=>({ 
  9.     sayName:()=>{ 
  10.         console.log('child'
  11.     } 
  12.   })) 
  13.     return <div>Child</div> 
  14. }} 

 

從createElement添加ref到React整個渲染過程的末尾(commit階段)被賦值前,這個ref都是同一份引用。

這也正如 ref單詞的本意 reference引用一樣。

小節(jié)總結(jié)

1.ref出現(xiàn)在組件上時是一個保留屬性

2.ref在組件存在的生命周期內(nèi)維護(hù)了同一個引用(可變對象 MutableObject)

3.當(dāng)ref掛載的對象是原生html標(biāo)簽時會ref對象的current屬性會被賦值為真實(shí)DOM 而如果是React組件會被賦值為React"組件實(shí)例"

4.ref掛載都在commit階段處理

創(chuàng)建ref的方式

ref prop相當(dāng)于在組件上挖了一個“坑” 來承接 ref對象,但是這樣還不夠我們還需要先創(chuàng)建ref對象

字符串ref & callback ref

這兩種創(chuàng)建ref的方式不再贅述,官網(wǎng)以及社區(qū)優(yōu)秀文章可供參考。

https://zh-hans.reactjs.org/docs/refs-and-the-dom.html

https://blog.logrocket.com/how-to-use-react-createref-ea014ad09dba/

createRef & useRef

createRef

16.3引入了createRef這個api

createRef的源碼就是一個閉包,對外暴露了 一個具有 current屬性的對象。

我們一般會這樣在class component中使用createRef

  1. class CreateRefComponent extends React.Component { 
  2.   constructor(props) { 
  3.     super(props); 
  4.     this.myRef = React.createRef() 
  5.   } 
  6.   componentDidMount() { 
  7.     this.myRef.current.focus() 
  8.     console.log(this.myRef.current
  9.     // dom input 
  10.   } 
  11.   render() { 
  12.     return <input ref={this.myRef} /> 
  13.   } 

為什么不能在函數(shù)組件中使用createRef

結(jié)合第一節(jié)的內(nèi)容以及 createRef的源碼,我們發(fā)現(xiàn),這不過就是在類組件內(nèi)部掛載了一個可變對象。因為類組件構(gòu)造函數(shù)不會被反復(fù)執(zhí)行,因此這個createRef自然保持同一份引用。但是到了函數(shù)組件就不一樣了,每一次組件更新, 因為沒有特殊處理createRef會被反復(fù)重新創(chuàng)建執(zhí)行,因此在函數(shù)組件中使用createRef將不能達(dá)到只有同一份引用的效果。

  1. const CreateRefInFC = () => { 
  2.   const valRef = React.createRef();  // 如果在函數(shù)組件中使用createRef 在這個例子中點(diǎn)擊后ref就會被重新創(chuàng)建因此將始終顯示為null 
  3.   const [, update] = React.useState(); 
  4.   return <div> 
  5.     value: {valRef.current
  6.     <button onClick={() => { 
  7.       valRef.current = 80; 
  8.       update({}); 
  9.     }}>+ 
  10.     </button> 
  11.   </div> 

 useRef

React 16.8中出現(xiàn)了hooks,使得我們可以在函數(shù)組件中定義狀態(tài),同時也帶來了 useRef

再來看moutRef和updateRef所做的事:

  1. function mountRef(initialValue) { 
  2.   var hook = mountWorkInProgressHook(); 
  3.   { 
  4.     var _ref2 = { 
  5.       current: initialValue 
  6.     }; 
  7.     hook.memoizedState = _ref2; 
  8.     return _ref2; 
  9.   } 
  10. function updateRef(initialValue) { 
  11.   var hook = updateWorkInProgressHook(); 
  12.   return hook.memoizedState; 

借助hook數(shù)據(jù)結(jié)構(gòu),第一次useRef時將創(chuàng)建的值保存在memoizedState中,之后每次更新階段則直接返回。

這樣在函數(shù)組件更新時重復(fù)執(zhí)行useRef仍返回同一份引用。

因此實(shí)際上和 createRef一樣本質(zhì)上只是創(chuàng)建了一個 Mutable Object,只是因為渲染方式的不同,在函數(shù)組件中做了一些處理。而掛載和卸載的行為全部交由組件本身來維護(hù)。

被擴(kuò)展的ref

從 createRef開始我們可以看到,ref對象的消費(fèi)不再和DOM以及組件屬性所綁定了,這意味著你可以在任何地方消費(fèi)他們,這也回答了本文一開始的那個問題。

useRef的應(yīng)用

解決閉包問題

由于函數(shù)組件每次執(zhí)行形成的閉包,下面這段代碼會始終打印1

  1. export const ClosureDemo =  () => { 
  2.     const [ count,setCount ] = useState(0); 
  3.     useEffect(()=> { 
  4.         const interval = setInterval(()=>{ 
  5.           setCount(count+1) 
  6.         }, 1000) 
  7.         return () => clearInterval(interval) 
  8.       }, []) 
  9.     // count顯示始終是1 
  10.     return <div>{ count }</div> 

 將 count 作為依賴傳入useEffect可以解決上面這個問題

  1. export const ClosureDemo =  () => { 
  2.     const [ count,setCount ] = useState(0); 
  3.     useEffect(()=> { 
  4.         const interval = setInterval(()=>{ 
  5.           setCount(count+1) 
  6.         }, 1000) 
  7.         return () => clearInterval(interval) 
  8.       }, [count]) 
  9.     return <div>{ count }</div> 

 但是這樣定時器也會隨著count值的更新而被不斷創(chuàng)建,一方面會帶來性能問題(這個例子中沒有那么明顯),更重要的一個方面是它不符合我們的開發(fā)語義,因為很明顯我們希望定時器本身是不變的。

另外一個方式也可以處理這個問題

  1. export const ClosureDemo =  () => { 
  2.     const [ count,setCount ] = useState(0); 
  3.     useEffect(()=> { 
  4.         const interval = setInterval(()=>{ 
  5.           setCount(count=> count + 1) // 使用setSate函數(shù)式更新可以確保每次都取到新的值 
  6.         }, 1000) 
  7.         return () => clearInterval(interval) 
  8.       }, []) 
  9.     return <div>{ count }</div> 

 這樣做確實(shí)可以處理閉包帶來的影響,但是僅限于需要使用setState的場景,對數(shù)據(jù)的修改和觸發(fā)setState是需要綁定的,這可能會造成不必要的刷新。

使用useRef創(chuàng)建引用

  1. export const ClosureDemo =  () => { 
  2.     const [ count,setCount ] = useState(0); 
  3.     const countRef = useRef(0); 
  4.     countRef.current = count 
  5.     useEffect(()=> { 
  6.         const interval = setInterval(()=>{ 
  7.           // 這里將更新count的邏輯和觸發(fā)更新的邏輯解耦了 
  8.           if(countRef.current < 5){ 
  9.             countRef.current++ 
  10.           } else { 
  11.             setCount(countRef.current
  12.           } 
  13.         }, 1000) 
  14.         return () => clearInterval(interval) 
  15.       }, []) 
  16.     return <div>{ count }</div> 

 封裝自定義hooks

useCreation

通過factory函數(shù)來避免類似于 useRef(new Construcotr)中構(gòu)造函數(shù)的重復(fù)執(zhí)行

  1. import { useRef } from 'react'
  2. export default function useCreation<T>(factory: () => T, deps: any[]) { 
  3.   const { current } = useRef({ 
  4.     deps, 
  5.     obj: undefined as undefined | T, 
  6.     initialized: false
  7.   }); 
  8.   if (current.initialized === false || !depsAreSame(current.deps, deps)) { 
  9.     current.deps = deps; 
  10.     current.obj = factory(); 
  11.     current.initialized = true
  12.   } 
  13.   return current.obj as T; 
  14. function depsAreSame(oldDeps: any[], deps: any[]): boolean { 
  15.   if (oldDeps === deps) return true
  16.   for (const i in oldDeps) { 
  17.     if (oldDeps[i] !== deps[i]) return false
  18.   } 
  19.   return true

usePrevious

通過創(chuàng)建兩個ref來保存前一次的state

  1. import { useRef } from 'react'
  2. export type compareFunction<T> = (prev: T | undefined, next: T) => boolean; 
  3. function usePrevious<T>(state: T, compare?: compareFunction<T>): T | undefined { 
  4.   const prevRef = useRef<T>(); 
  5.   const curRef = useRef<T>(); 
  6.   const needUpdate = typeof compare === 'function' ? compare(curRef.current, state) : true
  7.   if (needUpdate) { 
  8.     prevRef.current = curRef.current
  9.     curRef.current = state; 
  10.   } 
  11.   return prevRef.current
  12. export default usePrevious; 

useClickAway

自定義的元素失焦響應(yīng)hook

  1. import { useEffect, useRef } from 'react'
  2. export type BasicTarget<T = HTMLElement> = 
  3.   | (() => T | null
  4.   | T 
  5.   | null 
  6.   | MutableRefObject<T | null | undefined>; 
  7.    
  8.  export function getTargetElement( 
  9.   target?: BasicTarget<TargetElement>, 
  10.   defaultElement?: TargetElement, 
  11. ): TargetElement | undefined | null { 
  12.   if (!target) { 
  13.     return defaultElement; 
  14.   } 
  15.   let targetElement: TargetElement | undefined | null
  16.   if (typeof target === 'function') { 
  17.     targetElement = target(); 
  18.   } else if ('current' in target) { 
  19.     targetElement = target.current
  20.   } else { 
  21.     targetElement = target; 
  22.   } 
  23.   return targetElement; 
  24. // 鼠標(biāo)點(diǎn)擊事件,click 不會監(jiān)聽右鍵 
  25. const defaultEvent = 'click'
  26. type EventType = MouseEvent | TouchEvent; 
  27. export default function useClickAway( 
  28.   onClickAway: (event: EventType) => void, 
  29.   target: BasicTarget | BasicTarget[], 
  30.   eventName: string = defaultEvent, 
  31. ) { 
  32.   // 使用useRef保存回調(diào)函數(shù) 
  33.   const onClickAwayRef = useRef(onClickAway); 
  34.   onClickAwayRef.current = onClickAway; 
  35.   useEffect(() => { 
  36.     const handler = (event: any) => { 
  37.       const targets = Array.isArray(target) ? target : [target]; 
  38.       if ( 
  39.         targets.some((targetItem) => { 
  40.           const targetElement = getTargetElement(targetItem) as HTMLElement; 
  41.           return !targetElement || targetElement?.contains(event.target); 
  42.         }) 
  43. ) { 
  44.         return
  45.       } 
  46.       onClickAwayRef.current(event); 
  47.     }; 
  48.     document.addEventListener(eventName, handler); 
  49.     return () => { 
  50.       document.removeEventListener(eventName, handler); 
  51.     }; 
  52.   }, [target, eventName]); 

以上自定義hooks均出自ahooks

還有許多好用的自定義hook以及倉庫比如react-use都基于useRef自定義了很多好用的hook。

參考資料

  • React Fiber https://juejin.cn/post/6844903975112671239#heading-10
  • React 官網(wǎng)ref使用 https://zh-hans.reactjs.org/docs/refs-and-the-dom.html#gatsby-focus-wrapper
  • React 前生今世 https://zhuanlan.zhihu.com/p/40462264
  • React ref源碼分析 https://blog.csdn.net/qq_32281471/article/details/98473846

 

責(zé)任編輯:姜華 來源: Eval Studio
相關(guān)推薦

2025-04-02 07:29:14

2018-05-17 15:18:48

Logistic回歸算法機(jī)器學(xué)習(xí)

2024-07-07 21:49:22

2010-06-29 14:20:52

2024-03-27 10:14:48

2022-02-28 10:05:12

組件化架構(gòu)設(shè)計從原組件化模塊化

2020-04-28 22:12:30

Nginx正向代理反向代理

2023-08-03 08:03:05

2025-04-03 00:03:00

數(shù)據(jù)內(nèi)存網(wǎng)絡(luò)

2019-11-23 17:27:54

IO開源

2025-04-07 03:02:00

電腦內(nèi)存數(shù)據(jù)

2023-06-15 10:53:57

2023-02-07 08:55:04

進(jìn)程棧內(nèi)存底層

2025-03-14 12:30:00

Redis RDBRedis數(shù)據(jù)庫

2011-06-22 16:13:29

2011-06-22 16:35:59

2017-07-06 11:34:17

神經(jīng)形態(tài)計算人工智能突觸

2025-03-03 00:00:00

Chrome工具前端

2017-06-16 16:58:54

機(jī)器學(xué)習(xí)神經(jīng)形態(tài)架構(gòu)

2022-06-15 22:33:07

React逃生艙
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號