官網資料: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 的用法
