UseRef TypeScript-不能赋值给 LegacyRef < HTMLDivElement > 类型

我正在尝试使用 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>
}
67105 次浏览

Just import React:

import React, { useRef } from 'react';


function Test() {
const node = useRef<HTMLDivElement>(null);


if (
node &&
node.current &&
node.current.contains()
){ console.log("current accessed")}


return <div ref={node}></div>
}

I made an update. Use HTMLDivElement as generic parameter instead of HTMLElement | null. Also, contains expects an argument.

UPDATE useRef expects generic argument of DOM element type. You don't need to use | null because RefObject already knows that current might be null.

See next type:

interface RefObject<T> {
readonly current: T | null
}

TS & React are smart enough to figure out that your ref might be null

Key is to use HTMLElement and undefined for initialization

const node = useRef<HTMLElement>();

I came here looking for help with an iframe ref. Perhaps this solution will help someone else that's looking for the same thing. I replaced HTMLDivElement with HTMLIFrameElement so:

const node = useRef<HTMLIFrameElement>(null);

None of the above worked for me, but turns out the solution was quite simple...

All I was doing wrong was not explicitly including "null" as the parameter in the useRef initialization (it expects null, not undefined). Also you CANNOT use "HTMLElement" as your ref type, you have to be more specific, so for me it was "HTMLDivElement" for example).

So working code for me was something like this:

const ref = useRef<HTMLDivElement>(null);


return <div ref={ref}> Some Content... </div>

The same stands for the <svg> elements:

const ref = useRef<SVGSVGElement>(null)
...
<svg ref={ref} />
selfref = React.createRef<HTMLInputElement>()

I give the exacted TS Type, then the editor passed the check. it works nice now.