打字稿-转发和useref

时间:2020-10-10 22:43:54

标签: javascript reactjs typescript

我有两个组成部分:

const ComponentOne = () => {
   const a = React.useRef<ComponentTwo>(null);
                // ^^^^^^^^^^ throws error - ComponentTwo refers to a value but used as type here
   const fn = () => {
      a.current.open(); // how to type it so typescript knows than open() is a function

      a.current.awdokawd(); // typescript should throw error here
   };

   return (
      <ComponentTwo ref={a} />
   );
}

const ComponentTwo = React.forwardRef((props, ref: React.RefObject<What here?>) => {
                                                            // ^^^^ what to type here?
   React.useImperativeHandle(ref, () => ({
      open: () => {
         console.log('hey');
      },
   }));

   return (
      ...
   );
});

如您所见,我不确定使用useRef输入什么,因此打字稿可以正确识别组件及其方法。同样不确定使用forwardRef键入什么。

谢谢!

1 个答案:

答案 0 :(得分:3)

您只需为引用声明一个新类型:

interface ComponentTwoRef {
    open(): void;
}

const ComponentOne = () => {
   const a = React.useRef<ComponentTwoRef>(null);

   const fn = () => {
      a.current.open();

      a.current.awdokawd(); // typescript should throw error here
   };

   return (
      <ComponentTwo ref={a} />
   );
}

const ComponentTwo = React.forwardRef((props, ref: React.RefObject<ComponentTwoRef>) => {

   React.useImperativeHandle(ref, () => ({
      open: () => {
         console.log('hey');
      },
   }));

   return (
      ...
   );
});