【发布时间】:2022-08-14 03:02:35
【问题描述】:
当我按下 Tab.Navigator 中已选择的选项卡时,如何调用回调函数?
标签: react-native react-navigation
当我按下 Tab.Navigator 中已选择的选项卡时,如何调用回调函数?
标签: react-native react-navigation
import {EventArg, useNavigation, useRoute} from '@react-navigation/native';
import React from 'react';
export default function useTabDoublePressEffect(callback: Function) {
const navigation = useNavigation();
const route = useRoute();
React.useEffect(() => {
let current = navigation; // The screen might be inside another navigator such as stack nested in tabs
// We need to find the closest tab navigator and add the listener there
while (current && current.getState().type !== 'tab') {
current = current.getParent();
}
if (!current) {
return;
}
const unsubscribe = current.addListener(
// We don't wanna import tab types here to avoid extra deps
// in addition, there are multiple tab implementations
// @ts-expect-error
'tabPress',
(e: EventArg<'tabPress', true>) => {
// We should scroll to top only when the screen is focused
const isFocused = navigation.isFocused(); // In a nested stack navigator, tab press resets the stack to first screen
// So we should scroll to top only when we are on first screen
const isFirst =
navigation === current ||
navigation.getState().routes[0].key === route.key;
// Run the operation in the next frame so we're sure all listeners have been run
// This is necessary to know if preventDefault() has been called
requestAnimationFrame(() => {
if (isFocused && isFirst && !e.defaultPrevented) {
callback();
}
});
},
);
return unsubscribe;
}, [navigation, route.key]);
}
import React, {useState} from 'react';
import {Text} from 'react-native';
import useTabDoublePressEffect from '../hooks/useTabDoublePressEffect';
export default function SomeComponent() {
const [text, setText] = useState('Hello');
useTabDoublePressEffect(() => setText('Bye'));
return <Text>{text}</Text>;
}
【讨论】: