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

React Navigation 6 设置headerShown: false后如何获取Stack导航默认Header高度

问题原因

你配置了headerShown: false后,React Navigation不会渲染默认的Header组件,useHeaderHeight钩子是读取当前渲染的默认Header高度,所以返回值为0,属于正常逻辑。

解决方案

方案1:使用内置默认高度计算函数

直接调用React Navigation提供的getDefaultHeaderHeight工具函数获取官方默认导航栏高度,不受headerShown配置影响:

import { getDefaultHeaderHeight } from "@react-navigation/elements";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { Dimensions } from "react-native";

function CustomHeader() {
  // 配置项:当前页面是否为模态页
  const isModal = false;
  // 获取顶部安全边距,适配刘海屏、灵动岛等设备
  const insets = useSafeAreaInsets();
  // 获取屏幕宽度
  const screenWidth = Dimensions.get('window').width;

  // 计算得到默认导航栏高度
  const headerHeight = getDefaultHeaderHeight(isModal, insets.top, screenWidth);

  return (
    <View style={{ height: headerHeight }}>
      {/* 行内若干按钮... */}
      <View 
        style={{ 
          position: "absolute",
          alignSelf: "center",
          top: headerHeight/2
        }} 
      />
    </View>
  )
}

方案2:动态测量自定义Header高度(更通用)

如果你的自定义Header有自定义样式调整,不沿用默认高度,可以通过onLayout回调实时获取组件实际渲染高度,适配性更强:

import { useState } from "react";
import { View } from "react-native";

function CustomHeader() {
  const [headerHeight, setHeaderHeight] = useState(0);

  return (
    <View 
      onLayout={(e) => {
        // 实时获取当前Header的实际渲染高度
        const { height } = e.nativeEvent.layout;
        setHeaderHeight(height);
      }}
    >
      {/* 行内若干按钮... */}
      {headerHeight > 0 && (
        <View 
          style={{ 
            position: "absolute",
            alignSelf: "center",
            top: headerHeight / 2
          }} 
        />
      )}
    </View>
  )
}

优先选择方案2,不管后续如何调整自定义Header的样式,内部元素都能自动适配居中,不需要手动维护高度配置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 07:09:00