简体   繁体   English

Typescript & react-navigation:关于 NavigationContainer ref 的类型信息?

[英]Typescript & react-navigation: Type Information on NavigationContainer ref?

I am using react-navigation & I have encountered a use case where I need to navigate from outside a component (navigation after receiving push notification).我正在使用 react-navigation & 我遇到了一个用例,我需要从组件外部导航(接收推送通知后导航)。

The issue is, when using the navigation.navigate method from inside a component, I get proper Typescript Autocomplete and Intellisense based on all the types defined as per the documentation.问题是,当从组件内部使用navigation.navigate方法时,我会根据文档定义的所有类型获得正确的 Typescript 自动完成和 Intellisense。

However, when using the navigationRef.current?.navigate method, type information is absent.但是,当使用navigationRef.current?.navigate方法时,类型信息不存在。

Is there any way to bring type information to the ref object too?有什么方法可以将类型信息也带到参考 object 中吗?

You can do it by providing the generic type to the navigate method.您可以通过为navigate方法提供泛型类型来实现。

Let's say you have some screens and you declared the route name param list types ( taken from here ) like this:假设您有一些屏幕,并且您声明了路由名称参数列表类型( 取自此处),如下所示:

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

In order to get the type information about these routes in your navigate method, you can consume the above declared type as a generic, like this:为了在您的导航方法中获取有关这些路由的类型信息,您可以将上述声明的类型用作泛型,如下所示:

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

I also got the same issue while implementing push notification.What i'm done is, created a navigation helper file (navigationHelper.ts).我在实施推送通知时也遇到了同样的问题。我所做的是,创建了一个导航帮助程序文件 (navigationHelper.ts)。

import * as React from 'react';

export const navigationRef = React.createRef();

export function navigate(name, params) {
    navigationRef.current?.navigate(name, params);
}

in AppNavigator.tsx在 AppNavigator.tsx 中

import {navigate} from './helpers/NavigationHelper';从'./helpers/NavigationHelper'导入{navigate};

 messaging().onNotificationOpenedApp(remoteMessage => { console.log( 'Notification caused app to open from background state:', remoteMessage, ); let data = JSON.parse(remoteMessage?.data?.data); if (data?.page == 'ride_detail') { navigate('RideDetailsIndex', {id: data?.ride_id}); } });

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

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