iframe 的 useRef 使用什么类型

Ili*_*vic 6 iframe typescript reactjs

我想避免使用某种类型any,但我找不到应该使用什么类型定义:

const iframe = useRef<any>();

<iframe
    ref={iframe}
    sandbox='allow-scripts'
    srcDoc={rootHtml}
/>
Run Code Online (Sandbox Code Playgroud)

这样以后 Typescript 就可以识别iframe.current诸如 iframe.current.contentWindow和 之类的属性iframe.current.srcdoc,...

*编辑

如果我尝试HTMLIFrameElement按照建议使用,我会收到此错误ref={iframe}

类型 'MutableRefObject<HTMLIFrameElement | undefined>' 不可分配给类型 'LegacyRef | 不明确的'。类型 'MutableRefObject<HTMLIFrameElement | undefined>' 不可分配给类型“RefObject”。“当前”属性的类型不兼容。类型“HTMLIFrameElement | undefined' 不可分配给类型 >'HTMLIFrameElement | 无效的'。类型“未定义”不可分配给类型“HTMLIFrameElement |” >空'.ts(2322)

Bas*_*iat 3

我很惊讶将鼠标悬停在 vscode 中的 iframe ref 属性上没有为您提供类型HTMLIFrameElement

编辑:您还需要默认为 null,因为元素引用返回类型或 null 而不是未定义const f = useRef<HTMLIFrameElement>(null);