【问题标题】:Typescript & react-navigation: Type Information on NavigationContainer ref?Typescript & react-navigation:NavigationContainer ref 上的类型信息?
【发布时间】:2021-08-03 16:50:00
【问题描述】:

我正在使用 react-navigation 并且我遇到了一个用例,我需要从组件外部导航(收到推送通知后的导航)。

问题是,当在组件内部使用 navigation.navigate 方法时,我会根据文档中定义的所有类型获得正确的 Typescript Autocomplete 和 Intellisense。

但是,当使用navigationRef.current?.navigate 方法时,类型信息是缺失的。

有没有办法把类型信息也带入 ref 对象?

【问题讨论】:

    标签: javascript typescript react-native react-navigation react-navigation-v5


    【解决方案1】:

    您可以通过为navigate 方法提供泛型类型来实现。

    假设您有一些屏幕,并且您声明了路由名称参数列表类型 (taken from here),如下所示:

    type RootStackParamList = {
      Home: undefined;
      Profile: { userId: string };
      Feed: { sort: 'latest' | 'top' } | undefined;
    };
    

    为了在您的导航方法中获取有关这些路由的类型信息,您可以将上述声明的类型用作泛型,如下所示:

    // You will now be able to choose between 'Home' or 'Profile' or 'Feed' when invoking your navigate method
    navigationRef.current?.navigate<keyof RootStackParamList>('Home');
    

    【讨论】:

      猜你喜欢
      • 2021-09-22
      • 2020-04-24
      • 2021-03-06
      • 2021-03-17
      • 1970-01-01
      • 1970-01-01
      • 2022-08-07
      • 2022-10-23
      • 2022-12-13
      相关资源
      最近更新 更多