簡體   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