在React Native中处理Typescript中导航的更简洁方式

lvmkulzt  于 2022-12-19  发布在  React
关注(0)|答案(2)|浏览(209)

有谁知道一个更干净的方法呢{ navigation }:{navigation:React Native cli项目中的Typescript中的NativeStackNavigationProp}'?我已经尝试了许多与stackoverflow不同的方法,但它们都不起作用。

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>;
};
2ledvvac

2ledvvac1#

稍微清理代码的一种方法是使用类型Assert,而不是解构导航属性并显式定义其类型。例如,可以更改以下代码:
从这里:

const HomeScreen = ({ navigation }:{navigation: NativeStackNavigationProp<any>}) => {
    // code
};

对此:

const HomeScreen = (props: any) => {
    const navigation = props.navigation as NativeStackNavigationProp<any>;
    // code
};

或者,您可以定义自定义类型:

type HomeScreenProps = {
  navigation: NativeStackNavigationProp<any>;
};

并将其用作:

const HomeScreen = ({ navigation }: HomeScreenProps) => {
  // code
};
enxuqcxy

enxuqcxy2#

注:请注意,您需要使用React.FC对功能组件进行类型检查。

如果您参考React Navigation's guide,您将看到类型检查导航的正确方法是:

请先检查堆栈类型

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

const Stack = createNativeStackNavigator<RootStackParamList>();

键入检查屏幕

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

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

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

}

你可以用这两种方法中的任何一种,我总是用钩子,因为我觉得它更干净。

相关问题