首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Typescript - forward和useref

Typescript - forward和useref
EN

Stack Overflow用户
提问于 2020-10-11 06:43:55
回答 1查看 650关注 0票数 1

我有两个组件:

代码语言:javascript
复制
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输入什么,所以typescript可以正确地识别组件及其方法。我也不确定要用forwardRef输入什么。

谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-10-11 08:16:39

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

代码语言:javascript
复制
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 (
      ...
   );
});
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64298990

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档