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

React Native modal页无法跳转屏幕及嵌套导航路由传参报错

React Navigation Modal页面跳转及参数获取问题

初始场景与问题

  • 初始注册的Modal类型屏幕配置如下:
<Stack.Screen name="ForwardChatContent" component={ForwardChatContentScreen}
  options={{
    presentation: 'modal',
  }} />
  • 页面效果:
    Modal页面截图
  • 需求:从上述Modal页面push跳转到预先注册的ForwardChatToUser屏幕,该屏幕初始配置为:
<Stack.Screen name="ForwardChatToUser" component={ForwardChatToUserScreen}
  • 初始故障:直接调用navigate方法时,目标新屏幕无法正常展示。

尝试方案与新报错

为解决Modal内跳转问题,尝试将两个关联页面封装为独立栈导航器,代码如下:

const forwardStack = () => {
  return <Stack.Navigator>
    <>
      <Stack.Screen name="ForwardChatContent" component={ForwardChatContentScreen}
        options={{
          presentation: 'modal',
        }} />
      <Stack.Screen name="ForwardChatToUser" component={ForwardChatToUserScreen}
        options={{
          // presentation: 'modal',
        }} />
    </>
  </Stack.Navigator>
}

跳转调用代码:

RootNavigation.navigate('ForwardChat', {message : props.currentMessage})

新报错:在ForwardChatContent页面通过const message = route.params.message获取传入参数时抛出异常:

ERROR TypeError: undefined is not an object (evaluating 'route.params.message')

修复方案

1. 修正嵌套导航器配置

Modal本身是独立的模态挂载层,没有内置子栈容器,因此无法直接在Modal内部压入新页面,封装独立子栈的思路是正确的,但原有配置存在3处错误:

  • 自定义导航器组件必须大写开头,否则React会识别为原生标签无法渲染,将forwardStack重命名为ForwardStack
  • Modal的presentation: 'modal'配置需要移动到根栈注册子栈的层级,不要配置在子栈内部的屏幕上
  • Stack.Navigator的直接子元素必须是Stack.Screen,去掉多余的Fragment(<>...</>)包裹,同时指定子栈初始路由

正确配置代码如下:
根栈注册逻辑:

// 根栈导航器
<Stack.Navigator>
  {/* 原有其他屏幕注册保持不变 */}
  <Stack.Screen 
    name="ForwardChat" 
    component={ForwardStack}
    options={{ presentation: 'modal' }} // Modal配置移到此处
  />
</Stack.Navigator>

子栈ForwardStack逻辑:

const ForwardStack = () => {
  return (
    <Stack.Navigator initialRouteName="ForwardChatContent">
      <Stack.Screen name="ForwardChatContent" component={ForwardChatContentScreen} />
      <Stack.Screen name="ForwardChatToUser" component={ForwardChatToUserScreen} />
    </Stack.Navigator>
  )
}

2. 修正嵌套导航器的参数传递方式

调用navigate跳转到嵌套子栈时,如果不指定内部子路由,参数只会挂载到父级栈屏幕上,子屏幕无法直接读取。官方推荐跳转时明确指定子路由和对应参数:

RootNavigation.navigate('ForwardChat', {
  screen: 'ForwardChatContent', // 指定子栈内要打开的目标屏幕
  params: {
    message: props.currentMessage // 目标页面需要的参数放在params下
  }
})

修改后,ForwardChatContent页面内原有const message = route.params.message的取值逻辑可以正常运行,无需修改。

3. Modal内部页面跳转逻辑

配置完成后,在ForwardChatContent页面内跳转子栈内的ForwardChatToUser页面,直接调用导航方法即可:

// 普通导航,新页面入栈,返回时回到ForwardChatContent
navigation.navigate('ForwardChatToUser')
// 如果需要明确的压栈效果,也可以用push
navigation.push('ForwardChatToUser')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 23:45:54