自定义后退按钮行为不会导航到指定的屏幕

时间:2021-07-19 07:23:36

标签: react-native

所以我有一个带有多个屏幕的 TabNavigator,我正在尝试为消息屏幕中 Android 上的后退按钮创建自定义行为。此自定义行为适用于 console.logs,但在我尝试导航到主屏幕时不起作用。我使用了 react-navigation 文档中的代码片段,并根据需要对其进行了修改 (https://reactnavigation.org/docs/custom-android-back-button-handling/)。我想让 navigation.navigate('Home'); 工作。

TabNavigator

class Tabs extends React.Component 
{
  render()
  {
    // Create Bottom Tab Navigatior
    const Tab = createBottomTabNavigator();

    const { navigation } = this.props;
    return(
      <Tab.Navigator tabBar={props => <CustomTabBar {...props} />}>
        <Tab.Screen name="Home" component={HomeScreen} />
        <Tab.Screen name="Map" component={MapScreen} />
        <Tab.Screen name="Zap" component={ZapScreen}/>
        <Tab.Screen name="Explore" component={ExploreScreen} />
        <Tab.Screen name="Profile" component={ProfileScreen} />
        <Tab.Screen name="Post" component={PostScreen} />
        <Tab.Screen name="Settings" component={SettingsScreen} />
        <Tab.Screen name="Notifications" component={NotificationsScreen} />
        <Tab.Screen name="Messages" component={MessagesScreen} />
      </Tab.Navigator>
    )
  }
}

消息屏幕

import React from 'react';
import { View, Text, Button, StyleSheet, BackHandler } from 'react-native';
import { useFocusEffect } from '@react-navigation/native'
import styles from './MessagesScreenStyles';

const MessagesScreen = ({navigation}) => {

    useFocusEffect(
        React.useCallback(() => {
          const onBackPress = () => {
                console.log("onbackpress"); // This works
                navigation.navigate('Home'); // This does nothing, not even an error
          };
    
          BackHandler.addEventListener('hardwareBackPress', onBackPress);
    
          return () =>
            BackHandler.removeEventListener('hardwareBackPress', onBackPress);
        })
    );
    return(
        <View style = {styles.container}>
            <Text>MessagesScreen</Text>
        </View>
    );
};

export default MessagesScreen;

1 个答案:

答案 0 :(得分:0)

navigation.navigate 方法适用于 Stack 屏幕。试试 jump 方法。 https://reactnavigation.org/docs/tab-based-navigation#jumping-between-tabs