android - BackHandler 'hardwareBackPress 只工作一次 | react native

标签 android react-native react-native-navigation onbackpressed

我需要在 Android 设备上处理 Back Press,但我的 BackHandler 只工作一次。

这是我的代码 fragment -

 componentWillUnmount() {
        BackHandler.removeEventListener('hardwareBackPress', this.handleBackPress);
    }
    componentDidMount() {
        BackHandler.addEventListener('hardwareBackPress', this.handleBackPress);
    }

        handleBackPress = () => {

            console.log("handleBackPress Called on RootMenuView : current View ? : " + this.state.mainView);

            if (this.state.mainView === "Main"){
                return false;
            } else{
                this.state.mainView = "Main";
                this.forceUpdate();
                return true;
            }

        }

我需要在菜单 View 上处理这个,因为我需要在其他组件的后退时显示默认组件。

最佳答案

 componentWillUnmount() {
    BackHandler.removeEventListener('hardwareBackPress', this.handleBackPress);
   }
   componentDidMount() {
    BackHandler.addEventListener('hardwareBackPress', this.handleBackPress);
 }

    handleBackPress = () => {

        console.log("handleBackPress Called on RootMenuView : current View ? : " + this.state.mainView);

        if (this.state.mainView === "Main"){
            return false;
        } else{
             //not this
            //this.state.mainView = "Main";
            // use this
           this.setState({mainView: "Main"})
            this.forceUpdate();
            return true;
        }

    }

关于android - BackHandler 'hardwareBackPress 只工作一次 | react native ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53097721/

相关文章:

react-native - 如何在 React Native v.5(而非 v.4)中嵌套多个导航器

java - 如何从 Android 的内部存储中获取图像数组

android - 如何将ImageView对齐到底部,填充它的宽度和高度,并保持它的纵横比?

javascript - 限制 React Native TextInput 中的特殊字符

react-native - 如何获取一个 zip 文件并解压到 ram 中 react native

reactjs - 如何在 React Native 中显示一次屏幕?

java - 三星 Galaxy s3 上的旋转器问题

android - 在构建您的第一个应用程序教程中,什么是 "actionbar_background"以及如何定义它?

android - React-Native:gradlew 构建产生:react-native-fbsdk:lint 错误 "libraries must use the exact same version"

react-native - 在堆栈导航器托管的屏幕内访问 `headerRight`