简体   繁体   中英

Cleaner way to handle Navigation in Typescript in React Native

Anyone here who knows a cleaner way then ´{ navigation }:{navigation: NativeStackNavigationProp}` in Typescript in a React Native cli project? I already tried many different things from stackoverflow but they didn't work.

import * as React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import {createNativeStackNavigator, NativeStackNavigationProp} from '@react-navigation/native-stack';
import {Button, Text} from "react-native";

const Stack = createNativeStackNavigator();

export const App = () => {
    return (
        <MyStack/>
    );
};

const MyStack = () => {
    return (
        <NavigationContainer>
            <Stack.Navigator>
                <Stack.Screen
                    name="Home"
                    component={HomeScreen}
                    options={{ title: 'Welcome' }}
                />
                <Stack.Screen name="Profile" component={ProfileScreen} />
            </Stack.Navigator>
        </NavigationContainer>
    );
};

const HomeScreen = ({ navigation }:{navigation: NativeStackNavigationProp<any>}) => {
    return (
        <Button
            title="Go to Jane's profile"
            onPress={() =>
                navigation.navigate('Profile', { name: 'Jane' })
            }
        />
    );
};
const ProfileScreen = ({ navigation, route }:{navigation: NativeStackNavigationProp<any>, route: any}) => {
    return <Text>This is {route.params.name}'s profile!</Text>;
};

Note: Please note that you need to use React.FC to type check your functional components.

If you refer to React Navigation's guide you will see that the correct way of type checking your navigation is:

Type check your stack first

type RootStackParamList = {
  Home: { title: string };
  Profile: undefined;
};

const Stack = createNativeStackNavigator<RootStackParamList>();

Type check your screens

type Props = NativeStackScreenProps<RootStackParamList, 'Home'>;


const HomeScreen:React.FC<{navigation:Props['navigation']}> = ({ navigation }) => {
  // code
}

or

    type Props = NativeStackScreenProps<RootStackParamList, 'Home'>
    
    const HomeScreen = () => {
          // code
          const navigation = useNavigation<Props['navigation']>()

}

You can use either of the two ways, I always use the hook, since it feels more clean to me.

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