如何自定义React Native Expo Router的导航栏头部?
Expo Router 自定义顶部导航标题方案
一、单个页面内动态修改标题
使用useNavigation钩子获取导航实例,通过setOptions方法设置顶部标题及样式,适合需要根据页面数据动态调整标题的场景:
import { useNavigation } from 'expo-router'; import { View, Text } from 'react-native'; import React from 'react'; export default function DetailsPage() { const navigation = useNavigation(); React.useEffect(() => { navigation.setOptions({ title: '我的详情页', // 可选:自定义头部样式 headerStyle: { backgroundColor: '#f0f0f0', }, headerTitleStyle: { fontSize: 18, fontWeight: '600', }, }); }, [navigation]); return ( <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}> <Text>详情页面内容</Text> </View> ); }
二、通过布局文件统一配置栈内页面标题
在/app/details-page/_layout.tsx中,利用Stack组件的screenOptions或Stack.Screen的options属性,为整个栈或单个页面设置标题:
import { Stack } from 'expo-router'; export default function DetailsLayout() { return ( <Stack // 栈内所有页面的默认头部配置 screenOptions={{ headerStyle: { backgroundColor: '#2196F3', }, headerTitleStyle: { color: 'white', }, }} > {/* 单独覆盖index页面的标题 */} <Stack.Screen name="index" options={{ title: '自定义详情页标题', }} /> </Stack> ); }
三、完全自定义头部组件
如果需要更复杂的头部(比如添加操作按钮、自定义布局),可以通过headerTitle或header属性替换默认头部:
自定义标题组件
// 页面组件内设置 navigation.setOptions({ headerTitle: () => ( <View style={{ flexDirection: 'row', alignItems: 'center', gap: 8 }}> <Text style={{ color: '#ff5722', fontWeight: 'bold' }}>自定义</Text> <Text>标题</Text> </View> ), });
完全替换头部
// 在_layout.tsx的Screen配置中 <Stack.Screen name="index" options={{ header: () => ( <View style={{ height: 60, paddingHorizontal: 16, backgroundColor: '#eee', justifyContent: 'center', flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' }}> <Text>自定义头部</Text> <Text style={{ color: '#2196F3' }}>操作</Text> </View> ), }} />
内容的提问来源于stack exchange,提问作者Evilguy
相关产品推荐
相关产品推荐

