I am using React Navigation library for my application with the following structure:
const RootStack = createNativeStackNavigator<RootTabParamList>();
<NavigationContainer theme={appTheme}>
<RootStack.Navigator>
<RootStack.Screen name="Tabs" component={Tabs}/>
<RootStack.Screen name="Screen A" />
<RootStack.Screen name="Screen B"/>
<RootStack.Screen name="Screen C"/>
</RootStack.Navigator>
</NavigationContainer>
Tabs is a functional component that renders anothor Navigator like this:
<Tab.Navigator>
<Tab.Screen name="Home" component={HomeScreen} />
<Tab.Screen name="Settings" component={SettingsScreen} />
<Tab.Screen name="Exit" component={Exit} />
</Tab.Navigator>
When I press tab Exit I want to listen to 'tabPress' event to handle my logic. So following the document of React Navigation, in my Exit component I did that:
React.useEffect(() => {
return props.navigation.addListener('tabPress', (e) => {
console.log('Doing something when tabPress');
});
}, [props.navigation]);
Document link: https://reactnavigation.org/docs/bottom-tab-navigator#events
But I didn't get the desired result. The log line is not printed.
What's the solution for this issue?
CodePudding user response:
don't use the function in cleanup. it should be like this. cleanup only runs when component unmounts.
React.useEffect(() => {
const unsubscribe = props.navigation.addListener('tabPress', (e) => {
console.log('Doing something when tabPress');
});
return unsubscribe;
}, [props.navigation]);
CodePudding user response:
You can listen to the tabPress
event like this.
<Tab.Screen name="Home" component={HomeScreen}
listeners={({ navigation }) => ({
tabPress: (e) => {
e.preventDefault();
console.log('Doing something when tabPress');
},
})}
/>