react中使用useRef


 

官網資料:https://react.docschina.org/docs/hooks-reference.html#useref

useRef 返回一個可變的 ref 對象,其 .current 屬性被初始化為傳入的參數(initialValue)。返回的 ref 對象在組件的整個生命周期內保持不變。

 

這里着重記錄下 useRef + hook 的用法:

export default function Example () {
  const contentRef = useRef<HTMLIFrameElement>(null)

  useEffect(() => {
    $api.xxxxx(id)
    .then((res) => {
      const iframe: HTMLIFrameElement | null = contentRef.current
... }) }, [id]) return ( <div ref={contentRef}>舉個栗子</div> ) }

 

這里有個視頻詳細介紹了 useRef + useEffect 的用法

https://egghead.io/lessons/react-access-and-modify-a-dom-node-with-the-react-useref-and-useeffect-hooks

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM