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

如何解决StackScreen header配置TouchableOpacity时navigation.navigate报错问题

问题原因
  • options直接配置为对象时,无法获取React Navigation注入的navigation实例,你代码中调用的navigation属于未定义变量,因此触发undefined is not an object (evaluating 'navigation.navigate')报错。
  • 你当前的Stack路由栈中未注册Page3对应的路由,即便拿到navigation实例,跳转时也会触发路由匹配失败的报错。
修复方案

将options改为函数形式,React Navigation会自动将navigation作为参数注入该函数,同时补充Page3的路由注册即可,修复后代码如下:

<Stack.Navigator>
  <Stack.Screen name="Page1" component={Page1} />
  <Stack.Screen
    name="Page2"
    component={Page2}
    // 改为函数形式,接收注入的navigation参数
    options={({ navigation }) => ({
      headerRight: () => (
        <View>
          <TouchableOpacity
            onPress={() => navigation.navigate('Page3')}>
            <Image source={require('../assets/image.png')} />
          </TouchableOpacity>
        </View>
      )
    })}
  />
  {/* 补充Page3路由注册,注意提前导入Page3组件 */}
  <Stack.Screen name="Page3" component={Page3} />
  <Stack.Screen name="Page4" component={Page4} />
  <Stack.Screen name="Page5" component={Page5} />
</Stack.Navigator>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 04:24:00