“Can’t pass useRef to any elements” 的中文翻译是 “无法将useRef传递给任何元素”。

huangapple go评论58阅读模式
英文:

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 &#39;react&#39;

export function Test() {
  const ref = useRef&lt;HTMLDivElement&gt;()
  return &lt;div ref={ref} /&gt;
}

I get the following error:

Type &#39;MutableRefObject&lt;HTMLDivElement | undefined&gt;&#39; is not assignable to type &#39;LegacyRef&lt;HTMLDivElement&gt; | undefined&#39;.
  Type &#39;MutableRefObject&lt;HTMLDivElement | undefined&gt;&#39; is not assignable to type &#39;RefObject&lt;HTMLDivElement&gt;&#39;.
    Types of property &#39;current&#39; are incompatible.
      Type &#39;HTMLDivElement | undefined&#39; is not assignable to type &#39;HTMLDivElement | null&#39;.
        Type &#39;undefined&#39; is not assignable to type &#39;HTMLDivElement | null&#39;.ts(2322)

It seems that useRef is defined as

function useRef&lt;T = undefined&gt;(): MutableRefObject&lt;T | undefined&gt;

While ref attribute type is defined as

interface RefObject&lt;T&gt; {
    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&lt;HTMLDivElement&gt;(null)

huangapple
  • 本文由 发表于 2023年5月21日 04:50:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76297307.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定