簡體   English   中英

嵌套選項卡導航器中的 React Navigation header 標題

[英]React Navigation header title in nested tab navigator

我在 Stack Navigator 中有一個 Tab Navigator,我希望將 header 標題動態配置為所選選項卡的標題。 就像有 3 個選項卡:主頁、個人資料、添加項目,我希望 header 在主頁選項卡中的標題為“主頁”,在個人資料選項卡中的標題為“個人資料”。

我嘗試在根導航器上使用 onStateChange,在選項卡導航器上使用 setOptions,但 onStateChange 僅在嵌套導航器中可用,而在嵌套導航器中不可用。

他們無論如何我可以實現這個嗎?

導航器配置是:

const TabNav = (
   <Tab.Navigator>
      <Tab.Screen name='Home' component={HomeScreen}/>
      <Tab.Screen name='Profile' component={ProfileScreen}/>
      <Tab.Screen name='Add Item' component={AddItemScreen}/>
   </Tab.Navigator>
)

<NavigationContainer>
   <Stack.Navigator>
      <Stack.Screen name='Login' component={LoginScreen}/>
      <Stack.Screen name='App' component={TabNav}/>
   </Stack.Navigator>
</NavigationContainer>

我有一個與react-navigation v5 類似的導航層次結構,我想更改嵌套 TabNavigator 中視圖內的 Header 標題。 我最終通過使用dangerouslyGetParent()獲取 StackNavigator 的父導航項然后使用setOptions()來實現它。

所以這是 TabNav 中三個視圖之一的最小代碼:

import React, {useCallback} from 'react';
import { useNavigation, useFocusEffect } from '@react-navigation/native';

const HomeScreen = (props) => {

    // TabNav navigation item
    const navigation = useNavigation();

    // Effect will be triggered everytime the Tab changes 
    //      Mounting is not enough -> Tabs will not be unmount by change
    useFocusEffect(
        useCallback(() => {

            // Get StackNav navigation item
            const stackNavigator = navigation.dangerouslyGetParent();
            if(stackNavigator){

                // Actually set Title
                stackNavigator.setOptions({
                    title: "Home"
                });
            }
        }, [navigation])
    );
    return (
        /* Component Items */
    );
};

來自文檔https://reactnavigation.org/docs/screen-options-resolution/

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

function getHeaderTitle(route) {
  // If the focused route is not found, we need to assume it's the initial screen
  // This can happen during if there hasn't been any navigation inside the screen
  // In our case, it's "Feed" as that's the first screen inside the navigator
  const routeName = getFocusedRouteNameFromRoute(route) ?? 'Feed';

  switch (routeName) {
    case 'Feed':
      return 'News feed';
    case 'Profile':
      return 'My profile';
    case 'Account':
      return 'My account';
  }
}

<Stack.Screen
  name="Home"
  component={HomeTabs}
  options={({ route }) => ({
    headerTitle: getHeaderTitle(route),
  })}
/>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM