You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native使用@react-navigation/native-stack时navigation.push类型报错如何解决

这个报错是因为你没有为React Navigation声明路由栈的参数类型映射,仅给NativeStackScreenProps传入any作为泛型参数时,TypeScript无法正确识别允许跳转的页面名、以及对应页面可接收的参数结构,就会抛出参数不匹配的类型错误。

推荐解决方案(标准做法)
  • 第一步:定义全局路由参数映射
    新建@/types/navigation.ts文件,写入你整个导航栈所有页面的名称和对应参数类型:
import type { NativeStackScreenProps } from '@react-navigation/native-stack';

// 这里按你实际的路由栈写所有页面,键是页面名,值是该页面接收的参数类型,无参数就写undefined
export type RootStackParamList = {
  Home: undefined; // Home页面无入参
  ScreenName: { myParam: string }; // 你要跳转到的ScreenName页面的参数结构
  // 其他页面继续加即可
};

// 封装通用的页面Props类型,减少重复代码
export type RootStackScreenProps<T extends keyof RootStackParamList> = NativeStackScreenProps<RootStackParamList, T>;
  • 第二步:替换组件内的Props类型声明
    把你Home组件的Props泛型替换成上面定义的类型:
import type { RootStackScreenProps } from '@/types/navigation';

// 泛型传当前页面的名称即可
export default function Home({ navigation }: RootStackScreenProps<'Home'>) {
    return (
        <View style={styles.container}>
            <Button onPress={() => navigation.push('ScreenName', {myParam: 'stuff'})} title={'Go to ScreenName'}/>
        </View>
    );
}
  • 第三步(可选):注册全局类型,让useNavigation等hooks自动带类型
    在刚才的navigation.ts文件末尾追加全局声明:
declare global {
  namespace ReactNavigation {
    interface RootParamList extends RootStackParamList {}
  }
}

做完之后所有的导航相关API都会自动带类型提示,不会再出现这类参数错误。

临时规避方案

如果只是临时调试不想全量定义路由类型,可以用类型断言跳过校验,不推荐长期使用:

// 写法1:断言页面名
navigation.push('ScreenName' as never, {myParam: 'stuff'})

// 写法2:直接断言navigation对象为any
(navigation as any).push('ScreenName', {myParam: 'stuff'})

内容的提问来源于stack exchange,提问作者Infinite Recursion

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 10:45:01