React native navigation v5 tab press not working

让人想犯罪 __ 提交于 2021-02-18 11:45:11

问题


As seen on the code, tabPress is not called, am i doing it wrong or am i missing something, unfortunately i have not found any code samples for react navigation version 5.

<Tab.Navigator labeled={false} barStyle={{backgroundColor: '#ffffff', height: 55}} options={{
        tabPress: ({navigation}) => {
            console.log('nav tab press triggered')
        }
    }}>
        <Tab.Screen name={`DeviceNavigatorTab`} component={DeviceNavigator} options={{
            tabBarIcon: ({tintColor}) => <Image source={require('../../images/feather_home-menu.png')}
                                                style={{width: 26, height: 26, tintColor}}/>,
            tabPress: ({navigation}) => {
                console.log('tab press triggered')
            }
        }} tabPress={() => { console.log('prop tab pressed') }}/>
        <Tab.Screen name={`AlarmNavigatorTab`} component={AlarmNavigator} options={{
            tabBarIcon: ({tintColor}) => <Image source={require('../../images/feather_alert-circle.png')}
                                                style={{width: 26, height: 26, tintColor}}/>,
        }}/>
        <Tab.Screen name={`ProfileNavigatorTab`} component={ProfileNavigator} options={{
            tabBarIcon: ({tintColor}) => <Image source={require('../../images/feather_user.png')}
                                                style={{width: 26, height: 26, tintColor}}/>,
        }} />
    </Tab.Navigator>

回答1:


I found something new in documentation, that i have not seen before, this is the way to add listener to screen, every time user clicks on tab, it goes to first stack screen inside this tab

<Tab.Screen name={`DeviceNavigatorTab`} component={DeviceNavigator} options={{
                tabBarIcon: ({tintColor}) => <Image source={require('../../images/feather_home-menu.png')} style={{width: 26, height: 26, tintColor}}/>,
            }} listeners={({ navigation, route }) => ({
                tabPress: e => {
                    if (route.state && route.state.routeNames.length > 0) {
                        navigation.navigate('Device')
                    }
                },
            })}/>



回答2:


You need to listen/subscribe "tabPress" event as below in your component.

React.useEffect(() => {
  const unsubscribe = navigation.addListener('tabPress', e => {
    // Prevent default behavior
    e.preventDefault();

    // Do something manually
    // ...
  });

  return unsubscribe;
}, [navigation]);


来源:https://stackoverflow.com/questions/60742984/react-native-navigation-v5-tab-press-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!