首页 > 解决方案 > React Navigation 5 - 带有自定义标题的 createNativeStackNavigator

问题描述

我在反应本机应用程序上使用反应导航 5。我尝试将 NativeStackNavigator 与自定义标题一起使用。使用 React 导航 4 它可以工作,但使用 5 则不行。

反应导航4:

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

...

const _baseNavigationOptions = (props, icon, text) => {
    return ({
      headerTitle: () => <TitleComponent  {...props} config={someConfiguration}/>,
      headerStyle: {
        backgroundColor: '#6084AD',
      },
      headerTintColor: '#FFF'
    });
  }

...
const ConsumptionStackNavigator = createStackNavigator({
    Consumption: {
        screen: Consumption,
        navigationOptions: _baseNavigationOptions({name:'bars', type: 'font-awesome'}, 'My Consumptions')
    }
}

当我尝试对 reactNavigation 5 做同样的事情时,headerTitle 不起作用:

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

...

  return (
      <Stack.Navigator
        initialRouteName="Consumption"
        screenOptions={{
          headerTitleAlign: 'center'
        }}>
        <Stack.Screen
          name="Consumption"
          component={ComsumptionComponent}
          options={{ header: (props) => _baseNavigationOptions(props, {name:'bars', type: 'font-awesome'}, 'My Consumption') }}
        />
...

标题显示消耗而不是我的自定义组件。如果我尝试使用 headerRight 而不是 headerTitle,我会遇到同样的问题

你能帮助我吗 :)

标签: react-nativereact-navigation-stackreact-navigation-v5

解决方案


navigationOptions在 v4 代码中设置,但header在 v5 代码中。您需要设置options,而不是header

options={(props) => _baseNavigationOptions(props, {name:'bars', type: 'font-awesome'}, 'My Consumption')}

推荐阅读