React Native - 设备后退按钮处理 [英] React Native - Device back button handling

查看:38
本文介绍了React Native - 设备后退按钮处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查点击设备后退按钮时是否有多个屏幕在堆栈中.如果是,我想显示上一个屏幕,如果不是,我想退出应用程序.

I want to check if there are more than one screens are on stack when device back button is hit. If yes, I want to show previous screen and if no, I want to exit app.

我已经检查了许多示例,但那些使用 BackAndroidNavigator.但它们都被弃用了.BackHandlerBackAndroid 的替代品.我可以使用 props.navigation.goBack(null) 显示上一个屏幕.

I have checked number of examples but those use BackAndroid and Navigator. But both of them are deprecated. BackHandler is replacement for BackAndroid. And I can show previous screen by using props.navigation.goBack(null).

但是我找不到用于在堆栈中查找屏幕计数的代码.我不想使用已弃用的 Navigator

But I am unable to find code for finding screen count in stack. I don't want to use deprecated Navigator!

推荐答案

此示例将向您展示大多数流程中通常预期的后退导航.您必须根据预期行为将以下代码添加到每个屏幕.有2种情况:1. 如果堆栈中的屏幕超过 1 个,设备返回按钮将显示上一个屏幕.2.如果堆栈只有1个屏幕,设备返回按钮将退出应用程序.

This example will show you back navigation which is expected generally in most of the flows. You will have to add following code to every screen depending on expected behavior. There are 2 cases: 1. If there are more than 1 screen on stack, device back button will show previous screen. 2. If there is only 1 screen on stack, device back button will exit app.

案例 1:显示上一个屏幕

Case 1: Show previous screen

import { BackHandler } from 'react-native';

constructor(props) {
    super(props)
    this.handleBackButtonClick = this.handleBackButtonClick.bind(this);
}

componentWillMount() {
    BackHandler.addEventListener('hardwareBackPress', this.handleBackButtonClick);
}

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

handleBackButtonClick() {
    this.props.navigation.goBack(null);
    return true;
}

重要提示:不要忘记在构造函数中绑定方法并在 componentWillUnmount 中移除监听器.

Important: Don't forget to bind method in constructor and to remove listener in componentWillUnmount.

案例 2:退出应用

在这种情况下,无需处理要退出应用程序的屏幕上的任何内容.

In this case, no need to handle anything on that screen where you want to exit app.

重要提示:这应该只是屏幕上的堆栈.

Important: This should be only screen on stack.

这篇关于React Native - 设备后退按钮处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆