如何正确键入嵌套的 React Navigation 导航器?

问题描述 投票:0回答:2

对于我的顶级导航器,我有:

type NavigationParamList = {
  Instances: undefined;
  Default: undefined;
  Settings: undefined;
  Compose: undefined;
};

const AppStack = createNativeStackNavigator<NavigationParamList>();

<NavigationContainer theme={NavTheme}>
      <AppStack.Navigator initialRouteName="Default">
        <AppStack.Screen
          name="Instances"
          component={InstancesScreen}
        />
....

但是当我做类似的事情时:

navigation.navigate('Instances')

我得到:

No overload matches this call.
  Overload 1 of 2, '(...args: never): void', gave the following error.
    Argument of type 'string' is not assignable to parameter of type 'never'.
  Overload 2 of 2, '(options: never): void', gave the following error.
    Argument of type 'string' is not assignable to parameter of type 'never'.

我做错了什么以及如何让 TypeScript 最终满意?

typescript react-navigation
2个回答
0
投票

您遇到的错误是由于 TypeScript 无法推断“导航”对象的正确类型所致。要解决此问题,您需要向“导航”对象提供类型信息,以便 TypeScript 知道哪些屏幕可用于导航


0
投票

我会尽力回答,但如果可能的话,请提供问题的更多细节。 (更多代码片段)


完整代码:

import { createStackNavigator } from '@react-navigation/stack';

type RootStackParamList = {
  Profile: { userId: string };
};

const RootStack = createStackNavigator<RootStackParamList>();

function App(){
  return (
    <RootStack.Navigator initialRouteName="Home">
      <RootStack.Screen name="Home" component={Home} />
      <RootStack.Screen
        name="Profile"
        component={Profile}
        initialParams={{ userId: user.id }}
      />
      <RootStack.Screen name="Feed" component={Feed} />
    </RootStack.Navigator>
  );
}

如果您使用

useNavigation
,请不要忘记输入:

import type { NativeStackNavigationProp } from '@react-navigation/native-stack';

type ProfileScreenNavigationProp = NativeStackNavigationProp<
  RootStackParamList,
  'Profile'
>;

const navigation = useNavigation<ProfileScreenNavigationProp>();

不要忘记为您的

Profile
组件输入正确的内容:

import type { NativeStackScreenProps } from '@react-navigation/native-stack';

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

function ProfileScreen({ route, navigation }: Props) {
  // ...
}

阅读更多信息https://reactnavigation.org/docs/typescript/

© www.soinside.com 2019 - 2024. All rights reserved.