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

查看:341
本文介绍了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.

我检查了一些示例,但这些示例使用BackAndroid和Navigator.但是它们两个都已弃用. BackHandler替代了BackAndroid.而且我可以使用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).

但是我无法找到用于在堆栈中查找屏幕计数的代码.我不想使用不推荐使用的导航器!

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

推荐答案

此示例将向您显示向后导航,这在大多数流中通常是期望的.您必须根据预期的行为在每个屏幕上添加以下代码.有两种情况: 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:显示上一屏

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天全站免登陆