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

如何使用react-navigation让headerTitle居中?设置headerTitleStyle不生效

解决React Navigation中Header Title无法居中的问题

我帮你梳理下不同版本的React Navigation对应的解决方法,你之前配置的headerTitleStyle: { alignSelf: 'center' }没生效,大概率是版本适配问题或者缺少关键配置项:

针对 React Navigation 6.x/5.x(当前主流版本)

官方在这两个版本里提供了更直接的配置项,不用再折腾alignSelf,直接用headerTitleAlign就能搞定:

1. 全局设置所有页面标题居中

在Stack Navigator的screenOptions里配置,所有页面都会生效:

import { createStackNavigator } from '@react-navigation/stack';

const Stack = createStackNavigator();

function App() {
  return (
    <Stack.Navigator
      screenOptions={{
        headerTitleAlign: 'center' // 一键全局居中
      }}
    >
      <Stack.Screen name="Home" component={Home} />
    </Stack.Navigator>
  );
}

2. 仅单个页面设置标题居中

如果只想让Home页面的标题居中,就在对应的Stack.Screen的options里单独配置:

<Stack.Screen 
  name="Home" 
  component={Home}
  options={{ headerTitleAlign: 'center' }}
/>

针对 React Navigation 4.x 及更早版本

旧版本里默认的header布局会让alignSelf: 'center'被左右元素(比如返回按钮)挤压,需要额外配置:

方法一:全局启用居中布局预设

在创建StackNavigator时,添加headerLayoutPreset: 'center',同时配合headerTitleStyle:

const AppNavigator = createStackNavigator(
  {
    Home: { screen: Home }
  },
  {
    headerLayoutPreset: 'center',
    defaultNavigationOptions: {
      headerTitleStyle: {
        alignSelf: 'center'
      }
    }
  }
);

方法二:单个页面配置

给Home页面单独设置navigationOptions:

const AppNavigator = createStackNavigator({
  Home: {
    screen: Home,
    navigationOptions: {
      headerTitleStyle: {
        alignSelf: 'center'
      },
      headerLayoutPreset: 'center'
    }
  }
});

特殊情况:如果页面有自定义的headerLeft/headerRight

如果你的页面添加了自定义的左侧或右侧按钮,可能还是会影响标题居中,这时候可以直接自定义headerTitle组件:

navigationOptions: {
  headerTitle: () => (
    <View style={{ flex: 1, alignItems: 'center' }}>
      <Text style={{ fontSize: 20, fontWeight: '600' }}>Home</Text>
    </View>
  )
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:11:42