React - 使用 TypeScript 和功能组件的 useRef

React - useRef with TypeScript and functional component


我试图从 parent 组件调用 child 组件方法并且我试图使用 useRef。将来,SayHi 方法将更新 child 组件中的挂钩状态。不幸的是,我有无法处理的错误。

行:ref.current.SayHi();

Property 'SayHi' does not exist on type 'ForwardRefExoticComponent<{ name: string; } & RefAttributes<{ SayHi: () => void; }>>'.

行:

Type 'RefObject void; }>>>' is not assignable to type '((instance: { SayHi: () => void; } | null) => void) | RefObject<{ SayHi: () => void; }> | null | undefined'. Type 'RefObject void; }>>>' is not assignable to type 'RefObject<{ SayHi: () => void; }>'. Property 'SayHi' is missing in type 'ForwardRefExoticComponent<{ name: string; } & RefAttributes<{ SayHi: () => void; }>>' but required in type '{ SayHi: () => void; }'.


完整 test.tsx 文件:

import React, { useRef, forwardRef, useImperativeHandle, Ref } from 'react'

const Parent = () => {
    const ref = useRef<typeof Child>(null);
    const onButtonClick = () => {
      if (ref.current) {
        ref.current.SayHi();
      }
    };
    return (
      <div>
        <Child name="Adam" ref={ref}/>
        <button onClick={onButtonClick}>Log console</button>
      </div>
    );
  }

const Child = forwardRef((props: {name: string}, ref: Ref<{SayHi: () => void}>)=> {
  const {name} = props;
  useImperativeHandle(ref, () => ({ SayHi }));

  function SayHi() { console.log("Hello " + name); }

  return <div>{name}</div>;
});

我很想就这个话题寻求帮助。

您需要在别处提取引用类型:

interface RefObject {
  SayHi: () => void
}

然后在两个地方都引用它

const Child = forwardRef((props: {name: string}, ref: Ref<RefObject>)=> {
  const {name} = props;  
  useImperativeHandle(ref, () => ({ SayHi }));
  function SayHi() { console.log("Hello " + name); }

  return <div>{name}</div>;
});
const Parent = () => {
    const ref = useRef<RefObject>(null);
    const onButtonClick = () => {
      if (ref.current) {
        ref.current.SayHi();
      }
    };
    return (
      <div>
        <Child name="Adam" ref={ref}/>
        <button onClick={onButtonClick}>Log console</button>
      </div>
    );
}

只需将 ref 的声明替换为 const ref = useRef<{ SayHi: () => void }>(null);