英文:
Can't pass useRef to any elements
问题
以下是翻译好的部分:
为什么这个不编译?
import { useRef } from 'react'
export function Test() {
const ref = useRef<HTMLDivElement>()
return <div ref={ref} />
}
我得到以下错误:
Type 'MutableRefObject<HTMLDivElement | undefined>' is not assignable to type 'LegacyRef<HTMLDivElement> | undefined'.
Type 'MutableRefObject<HTMLDivElement | undefined>' is not assignable to type 'RefObject<HTMLDivElement>'.
Types of property 'current' are incompatible.
Type 'HTMLDivElement | undefined' is not assignable to type 'HTMLDivElement | null'.
Type 'undefined' is not assignable to type 'HTMLDivElement | null'.ts(2322)
似乎`useRef`被定义为
function useRef<T = undefined>(): MutableRefObject<T | undefined>;
而ref属性类型被定义为
interface RefObject<T> {
readonly current: T | null;
}
如果undefined和null是不同的类型,它应该如何工作?
英文:
Why doesn't this compile?
import { useRef } from 'react'
export function Test() {
const ref = useRef<HTMLDivElement>()
return <div ref={ref} />
}
I get the following error:
Type 'MutableRefObject<HTMLDivElement | undefined>' is not assignable to type 'LegacyRef<HTMLDivElement> | undefined'.
Type 'MutableRefObject<HTMLDivElement | undefined>' is not assignable to type 'RefObject<HTMLDivElement>'.
Types of property 'current' are incompatible.
Type 'HTMLDivElement | undefined' is not assignable to type 'HTMLDivElement | null'.
Type 'undefined' is not assignable to type 'HTMLDivElement | null'.ts(2322)
It seems that useRef
is defined as
function useRef<T = undefined>(): MutableRefObject<T | undefined>
While ref attribute type is defined as
interface RefObject<T> {
readonly current: T | null;
}
How is it ever supposed to work, if undefined and null are different types?
答案1
得分: 2
const ref = useRef<HTMLDivElement>(null)
英文:
Try this:
const ref = useRef<HTMLDivElement>(null)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论