简体   繁体   中英

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).

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.

However, when using the navigationRef.current?.navigate method, type information is absent.

Is there any way to bring type information to the ref object too?

You can do it by providing the generic type to the navigate method.

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).

import * as React from 'react';

export const navigationRef = React.createRef();

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

in AppNavigator.tsx

import {navigate} from './helpers/NavigationHelper';

 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}); } });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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