React中使用typescript的forwardRef

5

我使用 React 的 forwardRef 进行了 ref 转发,以下是我的代码:

interface PropsDummy {}

const ProfileMenu = forwardRef<HTMLInputElement, PropsDummy>((props, ref) => {
  console.log(ref.current);
}

但为什么会导致 TypeScript 错误?
Property 'current' does not exist on type '((instance: HTMLInputElement | null) => void) | MutableRefObject<HTMLInputElement | null>'

但是,如果我使用别名,那么当前的对象可以完美地运行而不会出现 TypeScript 错误。

interface PropsDummy {}

const ProfileMenu = forwardRef<HTMLInputElement, PropsDummy>((props, ref) => {
  const myRef = ref as React.RefObject<HTMLInputElement>;
  console.log(myRef.current);
}

如何在不出现 TypeScript 错误的情况下获取当前对象?

谢谢

1个回答

12
< p>这个代码无法运行的原因是 ForwardedRef 的类型被定义为:

type ForwardedRef<T> = ((instance: T | null) => void) | MutableRefObject<T | null> | null;

尝试只访问.current,而不进行某些类型检查是行不通的,因为您可以看到,ref可能是一个函数,而函数没有这样的属性(current)。
当您将对象转换为所期望的类型时,它可以正常工作,但请注意,引用可以是函数或对象(或null!),因此在尝试访问current属性之前,您应该进行检查。
这应该会起作用:
const ProfileMenu = forwardRef<HTMLInputElement, PropsDummy>((props, forwardedRef) => {
  if (forwardedRef != null && typeof forwardedRef !== 'function') {
    console.log(forwardedRef.current);
  }
  
  return (
    <div className="App" ref={forwardedRef}>
      <h1>Hello there</h1>
    </div>
  );
});

1
它能工作,但这是唯一的解决方案吗?我也遇到了与发帖者相同的问题,但在Child组件中使用了forwardedRef多次,我不想每次都检查forwardedRef是否为函数。有人知道另一个解决方案吗? - JunKim
@JunKim 将 .current 的值放入 useState 中,并将该状态传递给子组件。 - smac89

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接