为 React Native 防止硬件后退按钮 android [英] Preventing hardware back button android for React Native

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

问题描述

我想阻止用户返回上一个屏幕.所以我添加了代码,但这不起作用.有什么解决办法吗?看到警报弹出,但返回假"不起作用.

I want to prevent the user from going back to the previous screen. So I added code, but this does not work. Are there any solutions for this? The alert pop up is seen but "return false" does not work.

componentDidMount() {
   BackAndroid.addEventListener('hardwareBackPress', () => {
     Alert.alert("alert","alert")

      this.props.navigator.pop();

       return false;
   });

推荐答案

如果您想禁用默认的后退按钮行为,您需要返回 true.

You need to return true, if you want to disable the default back button behavior.

这是一个示例组件,它将阻止用户返回上一屏幕.

Here is a sample component which will block the user from going back to previous screen.

import React, {Component,} from 'react';
import {
    View,
    Text,
    BackHandler,
    ToastAndroid,
} from 'react-native';

class BackButtonDemo extends Component {
    componentDidMount() {
        BackHandler.addEventListener('hardwareBackPress', this.handleBackButton);
    }

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

    handleBackButton() {
        ToastAndroid.show('Back button is pressed', ToastAndroid.SHORT);
        return true;
    }

    render() {
        return (
            <View>
                <Text>Back button example</Text>
            </View>
        );
    }
}

module.exports = BackButtonDemo;

注意:

同时从您的解决方案中删除 this.props.navigator.pop();.

Also remove this.props.navigator.pop(); from your solution.

Navigator 弹出函数会将用户带到由 Navigator 呈现的上一个屏幕.

Navigator pop function will take the user to the previous screen rendered by Navigator.

这篇关于为 React Native 防止硬件后退按钮 android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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