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