对于我的顶级导航器,我有:
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 无法推断“导航”对象的正确类型所致。要解决此问题,您需要向“导航”对象提供类型信息,以便 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) {
// ...
}