React Native 导航 TypeScript 类型定义
我在为一个期望参数的组件输入 props 时遇到了问题。我已经阅读了文档并遵循了指南。这是我的接收参数的组件。
type PoiDetailsProps = NativeStackScreenProps<RootStackParamList, 'PoiDetails'>;
const PoiDetails = (props: PoiDetailsProps) => {
我的 RootStackParamList:
export type RootStackParamList = {
Home: undefined;
Profile: undefined;
Drawer: undefined;
Login: undefined;
PoiDetails: {
placeDetails: PlaceDetail | null;
};
};
我的根导航
const Stack = createStackNavigator();
const RootNavigator = () => {
const {user} = useAppContext();
return (
<NavigationContainer>
{user ? (
<Stack.Navigator initialRouteName="Tabs">
<Stack.Screen
name="Tabs"
component={TabNavigator}
options={{headerShown: false}}
/>
<Stack.Screen name="Home" component={Home} />
<Stack.Screen name="PoiDetails" component={PoiDetails}/>
</Stack.Navigator>
) : (
<AuthStack />
)}
</NavigationContainer>
);
};
"@react-navigation/bottom-tabs": "^6.5.20", "@react-navigation/drawer": "^6.7.2", "@react-navigation/native": "^6.1.18", "@react-navigation/native-stack": "^6.10.1", "@react-navigation/stack": "^6.4.1",
我尝试了包括在内的不同方式来输入路线和导航
type PoiNavigationProps = NativeStackNavigationProp<
RootStackParamList,
'PoiDetails'
>;
type PoiRouteProps = RouteProp<RootStackParamList, 'PoiDetails'>;
type PoiDetailsProps = {
navigation: PoiNavigationProps;
route: PoiRouteProps;
};
我得到的错误是
类型 '{ route: RouteProp
我也尝试过在 RootNavigator 中为 placeDetails 提供初始值,我尝试将 RootStackParamList 中的 params 定义为类型 PlaceDetail | undefined。我也尝试过这些解决方案:React Native 与 TypeScript - 如何在 TypeScript 中使用来自 @react-navigation/native 的 useRoute
答案#1
类型推断来自 const Stack=createStackNavigator();。
我怀疑你需要像这样传入你的 RootStackParamList 类型:const Stack=createStackNavigator<RootStackParamList>();
请查看文档,它们非常有帮助:https://reactnavigation.org/docs/typescript/