【问题标题】:how to declare the type in my functional component?如何在我的功能组件中声明类型?
【发布时间】:2021-06-20 04:31:25
【问题描述】:

我想以这种方式在我的组件中声明类型,我已经看到使用类可以做到这一点,但是如何使用函数式组件来实现呢?无需导出界面?我已经研究了很多,但没有发现任何关于它的信息。

const Elem1 = forwardRef((props : any, ref : { open()? : void }) => {
   useImperativeHandle(ref, () => ({
       open: () => console.log('opened')
   }))

   ....
})

const Elem2 = () => {
    const elem1Ref = useRef<Elem1>()

    elem1Ref?.current?.open()

    ....
}

【问题讨论】:

    标签: javascript typescript react-native ecmascript-6


    【解决方案1】:

    如果我猜对了,您应该使用forwardRef 的 TS 泛型定义提供的类型参数。像这样?

    const Elem1 = forwardRef<YourRefType, YourPropsType>((props, ref) => {
      ...
    }
    
    

    【讨论】:

    • 我已经尝试过使用这种语法,但是 VS Code 在 useRef 中提供了这个错误:'Elem1' 指的是一个值,但在这里被用作一个类型。您的意思是“typeof Elem1”吗?
    【解决方案2】:

    我一直在研究,根据他们的说法,无法声明功能组件的类型,只需导出组件的单独接口,无论如何,谢谢!

    【讨论】:

      猜你喜欢
      • 2019-12-05
      • 2021-01-30
      • 2020-08-20
      • 2016-11-18
      • 2017-09-14
      • 2023-01-15
      • 2019-11-01
      • 2015-10-07
      相关资源
      最近更新 更多