【问题标题】:BackHandler in react native not working properlyReact Native 中的 BackHandler 无法正常工作
【发布时间】:2021-10-08 14:52:09
【问题描述】:

我正在尝试在反应本机堆栈导航中实现返回处理程序。 我有 闪屏、首页、演示

在主屏幕中,我在后按时退出应用程序功能。当我从主屏幕按下返回按钮时,此函数正在调用。

但是当我从演示屏幕按下返回按钮时,也会调用这个退出函数。请帮我看看我的代码有什么问题..

这是我的 App.js

<NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen
          name="splashScreen"
          component={splashScreen}
          options={{headerShown: false}}
        />

        <Stack.Screen
          name="Home"
          component={Home}
          options={{headerShown: true}}
        />
        <Stack.Screen
          name="Demo"
          component={Demo}
          options={{headerShown: true}}
        />
      </Stack.Navigator>
    </NavigationContainer>

这是我的 Home.js

export default class Home extends Component {
  handleBackButton = () => {
    Alert.alert(
      'Exit App',
      'Exiting the application?',
      [
        {
          text: 'Cancel',
          onPress: () => console.log('Cancel Pressed'),
          style: 'cancel',
        },
        {
          text: 'OK',
          onPress: () => BackHandler.exitApp(),
        },
      ],
      {
        cancelable: false,
      },
    );
    return true;
  };

  componentDidMount() {
    BackHandler.addEventListener('hardwareBackPress', this.handleBackButton);
  }

  componentWillUnmount() {
    BackHandler.removeEventListener('hardwareBackPress', this.handleBackButton);
  }

render(){
return()
}

这里是 Demo.js

handleBackButton = () => {
    this.props.navigation.navigate('Home');
  };

  componentDidMount() {
    BackHandler.addEventListener('hardwareBackPress', this.handleBackButton);
  }

  componentWillUnmount() {
    BackHandler.removeEventListener('hardwareBackPress', this.handleBackButton);
  }
render(){
return()
}

【问题讨论】:

    标签: javascript react-native handler back stack-navigator


    【解决方案1】:

    快速解决方法是

    handleBackButton = () => {
      if(!this.props.navigation.isFocused()){
        return false
      }
      //rest of your codes
    }
    

    【讨论】: