如何找出哪个选项卡在 React Navigation TopTabNavigator 中处于活动状态



这是我的代码:

const Tab = createMaterialTopTabNavigator();
<Tab.Navigator
initialRouteName="Page1"
tabBarOptions={{
activeTintColor: '#000000',
labelStyle: { fontSize: 12 },
style: { backgroundColor: 'rgb(255, 255, 255)', height: 45},
}}
>

<Tab.Screen
name="Page2"
component={Page2}

options={{ tabBarLabel: 'Page2' }}
/>
<Tab.Screen
name="Page3"
component={Page3}
options={{ tabBarLabel: 'Page3' }}
/>
</Tab.Navigator>

所以这是我的问题,我需要知道哪个选项卡在给定时间处于活动状态才能从数据库中接收一些数据。理想情况下,状态包含活动选项卡的 id 或名称。

感谢您的帮助

你可以实现一个自定义钩子,它使用 React Navigation 中的 useFocusEffect 钩子。然后,您可以将此自定义挂钩提供给屏幕。

const useCustomHookOnFocus = () => {
useFocusEffect(
React.useCallback(() => {
const unsubscribe = API.subscribe(userId, user => setUser(user));
return () => unsubscribe();
}, [])
);
};
const YourScreen = () => {
useCustomHookOnFocus();
}

您还可以获取导航状态并检查您是否在屏幕中,如下所示:

const state = useNavigationState(state => state);
state.routes.map((route, index) => {
const isFocused = state.index === index;
}

最新更新