React - useRef 与 TypeScript 和功能组件

Ada*_*cki 21 ref typescript reactjs tsx react-functional-component


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

行:ref.current.SayHi();

类型“ForwardRefExoticComponent<{ name: string;”上不存在属性“SayHi” } & RefAttributes<{ SayHi: () => void; }>>'。

行:< Child name="Adam" ref={ref}/>

输入'RefObject void; }>>>' 不能分配给类型 '((instance: { SayHi: () => void; } | null) => void) | RefObject<{ SayHi: () => void; }> | 空| 不明确的'。输入'RefObject void; }>>>' 不能分配给类型 'RefObject<{ SayHi: () => void; }>'。“ForwardRefExoticComponent<{ name: string;”类型中缺少“SayHi”属性 } & RefAttributes<{ SayHi: () => void; }>>' 但在类型 '{ 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>;
});
Run Code Online (Sandbox Code Playgroud)

我深切地寻求有关此主题的帮助。

Fed*_*kun 39

您需要在别处提取 ref 类型:

interface RefObject {
  SayHi: () => void
}
Run Code Online (Sandbox Code Playgroud)

然后在两个地方都引用它

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>;
});
Run Code Online (Sandbox Code Playgroud)
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>
    );
}
Run Code Online (Sandbox Code Playgroud)