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

React Navigation:headerLeft组件无法获取navigation如何实现返回?

解决React Navigation 5中headerLeft无法获取navigation对象实现返回的问题

在React Navigation 5中,你当前的headerLeft配置是无参箭头函数,因此无法获取到navigation对象。只需让headerLeft的函数接收React Navigation传递的参数(其中包含navigation实例),就能实现返回操作。

修改后的代码示例

const sharedHeaderOptions: StackNavigationOptions = {
  headerShown: true,
  headerTitleStyle,
  headerTitleAlign: 'left',
  headerTitleContainerStyle,
  headerLeftContainerStyle: headingStyles?.headerLeftContainerStyle,
  // 接收包含navigation的参数对象
  headerLeft: ({ navigation }) => (
    <TouchableOpacity
      onPress={() => {
        console.log('go back');
        navigation.goBack();
      }}>
      <BackChevron />
    </TouchableOpacity>
  ),
  headerBackImage: () => {},
  headerBackTitleVisible: false,
  headerTintColor: colors.INACTIVE_THUMBCOLOR,
};

额外优化建议

如果需要避免在栈内仅存一个页面时调用goBack()报错,可以添加判断逻辑:

headerLeft: ({ navigation }) => {
  // 仅当栈中存在可返回页面时渲染返回按钮
  if (!navigation.canGoBack()) {
    return null;
  }
  return (
    <TouchableOpacity
      onPress={() => navigation.goBack()}>
      <BackChevron />
    </TouchableOpacity>
  );
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 08:17:37