最佳答案
我正在尝试使用 useRef
和 TypeScript,但是遇到了一些麻烦。
用我的 RefObject
(我假设)我需要访问 current
。(即 node.current
)
我试过以下方法
const node: RefObject<HTMLElement> = useRef(null);
const node = useRef<HTMLElement | null>(null);
但是当我去设置 ref
时,我总是被告知 Xis not assignable to type 'LegacyRef<HTMLDivElement> | undefined'.
return <div ref={ node }>{ children }</div>
编辑: 这不应该限制在任何一种类型的元素,所以不仅仅是 HTMLDivElement | HTMLFormElement | HTMLInputElement
编辑: 这应该作为一个例子
import React, { useRef, RefObject } from 'react';
function Test()
{
// const node = useRef(null);
// const node: RefObject<HTMLElement> = useRef(null);
const node = useRef<HTMLElement | null>(null);
if (
node &&
node.current &&
node.current.contains()
){ console.log("current accessed")}
return <div ref={ node }></div>
}