React+Typescript中useNavigate传参后route与navigation类型报错如何解决
解决方案
第一步:定义全局路由参数映射
首先你需要全局声明所有路由页面对应的入参类型,通常可以放在navigation.d.ts全局类型文件中:
import type { StackScreenProps } from '@react-navigation/stack'; // 此处按你的实际路由列表补充完整,键为路由名称,值为对应页面接收的参数类型 export type RootStackParamList = { // 无参数的页面定义为undefined Home: undefined; // Stats页面接收字符串类型的userID参数 Stats: { userID: string }; }; // 直接导出Stats页面的Props类型方便复用 export type StatsScreenProps = StackScreenProps<RootStackParamList, 'Stats'>;
如果你使用的不是栈导航(比如底部标签导航、抽屉导航),只需把StackScreenProps替换为对应导航器的类型,比如BottomTabScreenProps、DrawerScreenProps即可。
第二步:给Stats页面组件的Props指定类型
直接导入上面定义的StatsScreenProps类型绑定到组件参数上即可:
import type { StatsScreenProps } from '你的全局类型文件路径'; function StatsPage({ route, navigation }: StatsScreenProps) { // 这里userID会自动推断为string类型,不会再触发隐式any报错 const { userID } = route.params; // 其他业务逻辑 }
可选:单独为两个参数声明类型
如果你不想复用统一的Props类型,也可以分别为route和navigation指定类型:
import type { RouteProp } from '@react-navigation/native'; import type { StackNavigationProp } from '@react-navigation/stack'; import type { RootStackParamList } from '你的全局类型文件路径'; type StatsRouteProp = RouteProp<RootStackParamList, 'Stats'>; type StatsNavigationProp = StackNavigationProp<RootStackParamList, 'Stats'>; function StatsPage({ route, navigation }: { route: StatsRouteProp, navigation: StatsNavigationProp }) { const { userID } = route.params; }
补充提示
如果你是Web端的React Router而非React Native的React Navigation,接收参数的方式和类型声明会有所不同:
import { useLocation } from 'react-router-dom'; type LocationState = { userID: string } function StatsPage() { const { state } = useLocation() as LocationState; const userID = state.userID; }
内容的提问来源于stack exchange,提问作者GrillOwner69420
相关产品推荐
相关产品推荐

