繁体   English   中英

打字稿 - 转发和用户引用

[英]Typescript - forward and useref

我有两个组成部分:

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输入什么,因此useRef正确识别组件及其方法。 也不确定用forwardRef输入什么。

谢谢!

你只需要为 ref 声明一个新类型:

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 (
      ...
   );
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM