我在Stack Navigator中有一个Tab Navigator,并且我希望将标题动态地配置为所选标签的标题。就像这里有3个标签一样:“首页”,“配置文件”,“添加项目”,我希望标题标签在“主页”标签中时为“主页”,在标题页中为“个人资料”。
我尝试在根导航器上使用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>
答案 0 :(得分:4)
我在react-navigation
v5上具有类似的导航层次结构,我想在嵌套的TabNavigator中的视图内更改页眉标题。我终于通过使用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 */
);
};
答案 1 :(得分:0)
来自文档 https://reactnavigation.org/docs/screen-options-resolution/
npm i -S lodash