在嵌套选项卡导航器中反应导航标题标题 [英] React Navigation header title in nested tab navigator

查看:70
本文介绍了在嵌套选项卡导航器中反应导航标题标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Stack Navigator 中有一个 Tab Navigator,我希望将标题标题动态配置为所选选项卡的标题.就像有 3 个选项卡:主页、个人资料、添加项目,我希望标题在主页选项卡中为主页",在个人资料选项卡中为个人资料".

I have a Tab Navigator inside a Stack Navigator and I want the header title to be dynamically configured as the title of the tab selected. Like there's 3 tabs: Home, Profile, Add Item and I want the header title to be "Home" when in the home tab, "Profile" when in the profile tab.

我尝试在根导航器上使用 onStateChange 并在选项卡导航器上使用 setOptions 但 onStateChange 仅在嵌套导航器中可用,而在嵌套导航器中不可用.

I tried using onStateChange on the root navigator and setOptions on the tab navigator but onStateChange is only available in the and not in the nested navigators.

他们无论如何我可以存档吗?

Is their anyway I can archieve this?

导航器配置是:

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 中更改视图内的标题标题.我最终通过使用 dangerouslyGetParent() 获取 StackNavigator 的父导航项然后使用 setOptions() 来实现它.

I had a similar Navigation hierarchy with react-navigation v5 and I wanted to change the Header Title inside a View in the nested TabNavigator. I finally achieved it by getting the parent navigation item of the StackNavigator with dangerouslyGetParent() and then using setOptions().

所以这是 TabNav 中三个视图之一的最小代码:

So here is your minimal Code for one of the three views inside your 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 */
    );
};

这篇关于在嵌套选项卡导航器中反应导航标题标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆