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



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

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最终只是快乐?

我会尽量回答,不过如果可能的话,请详细说明这个问题。(更多代码片段)

整个代码:

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/阅读更多信息

你遇到的错误是由于TypeScript无法推断出'navigation'对象的正确类型。要解决这个问题,你需要为'navigation'对象提供类型信息,以便TypeScript知道哪些屏幕可用于导航

最新更新