官网资料: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 的用法