首页 > 解决方案 > 类型 '((instance: HTMLDivElement | null) => void) | 上不存在属性 'current' 参考对象'

问题描述

通常当我使用 React + Typescript 并且我必须使用 refs 时,我通常会使用这个检查:

const ref = useRef<HTMLDivElement>(null)
...
if(ref && ref.current)

但最近,我收到了这个错误:

Property 'current' does not exist on type '((instance: HTMLDivElement | null) => void) | RefObject<HTMLDivElement>'.
  Property 'current' does not exist on type '(instance: HTMLDivElement | null) => void'.ts(2339)

关于这个错误意味着什么的任何想法?为了解决这个问题,作为一种解决方法,我添加了第三个检查:

if(ref && "current" in ref && ref.current)

但这看起来很糟糕,主要是当您必须同时使用多个 refs 时。

谢谢你的帮助。

标签: javascriptreactjstypescript

解决方案


现代 React 中有两种 ref:ref 对象和 ref 回调。Ref 对象是由useRef(或在类组件中createRef)创建的:它是具有current属性的对象。在打字稿中,这些具有 type RefObject<T>,其中T任何值将 on current

Ref 回调是另一种选择,某些高级案例需要它。您将一个函数传递给元素,该函数将在创建或销毁实例时回调。这些都有类型(instance: T) => void

将 ref 对象和 ref 回调组合成一个类型的简写是Ref<T>,看起来这就是您的代码所期望的。由于您尚未显示该代码,因此我必须对其外观进行一些有根据的猜测。假设您有一个接受 ref 作为 prop 的组件(也许它可以将它交给它的内部组件之一):

interface ExampleProps {
  buttonRef: Ref<HTMLButtonElement>
}

const Example: FC<ExampleProps> = ({ buttonRef }) => {
  return (
    <div>
      <button ref={buttonRef}>Hello</button>
    <div>
  )
}

由于我已将 prop 定义为 Ref,因此可以在 ref 对象或 ref 回调中传递它。在这种情况下这很好,因为除了将它传递给按钮之外,我没有对它做任何事情。但是如果我尝试编写一些代码来与之交互,我不能假设它是一个对象或函数。

如果我需要这样做,也许我可以限制道具,所以它只需要 ref 对象,然后我可以假设它会有.current

interface ExampleProps {
  buttonRef: RefObject<HTMLButtonElement>
}

const Example: FC<ExampleProps> = ({ buttonRef }) => {
  useEffect(() => {
    console.log(buttonRef.current);
  });
  return (
    <div>
      <button ref={buttonRef}>Hello</button>
    <div>
  )
}

但也许我不想限制我的组件的使用方式,但我仍然需要能够以某种方式与 ref 交互。在这种情况下,我可能需要自己创建一个回调 ref,然后向其中添加逻辑来处理我对 ref 的使用以及 prop 对 ref 的使用:

interface ExampleProps {
  buttonRef: Ref<HTMLButtonElement>
}

const Example: FC<ExampleProps> = ({ buttonRef }) => {
  const myRef = useRef<HTMLButtonElement>(null);
  useEffect(() => {
    console.log(myRef.current);
  });
  return (
    <div>
      <button ref={(element) => {
        (myRef as MutableRefObject<HTMLButtonElement>).current = element;
        if (typeof buttonRef === 'function') {
          buttonRef(element);
        } else {
          buttonRef.current = element;
        }
      }}>Hello</button>
    <div>
  )
}

的类型断言as MutableRefObject<HTMLButtonElement>是必需的,因为myRef它被标记为不可变。这种类型反映了只有 react 才应该修改.current属性的事实。这对于正常的用例来说是好的,但是由于我们从 react 中接管了这个责任,所以改变值是可以的。


推荐阅读