繁体   English   中英

如何在 React-native 中使用 Backhandler

[英]How to use Backhandler in React-native

当我什至触摸 Android 后退按钮两次时,我无法退出应用程序。 只是卡在第一个底部标签中。

屏幕上有四个按钮到 go 到每个视图。(在同一 class 组件中)

当你调用 BackHandler.exitApp(); 应用程序将关闭,但仍将保留在 android 的最近选项卡中。

BackHandler.exitApp();

在这里,我将分享一个 react-native BackHandler api 的例子。 当您想通过单击返回按钮退出应用程序时,您应该使用hardwareBackPress EventListener,让我们通过一个示例来说明。

import React, { Component } from "react";
import { Text, View, StyleSheet, BackHandler, Alert } from "react-native";

class App extends Component {

  backAction = () => {
    Alert.alert("Hold on!", "Are you sure you want to go back?", [
      {
        text: "Cancel",
        onPress: () => null,
        style: "cancel"
      },
      { text: "YES", onPress: () => BackHandler.exitApp() }
    ]);
    return true;
  };

  componentDidMount() {
    this.backHandler = BackHandler.addEventListener(
      "hardwareBackPress",
      this.backAction
    );
  }

  componentWillUnmount() {
    this.backHandler.remove();
  }

  render() {
    return (
      <View style={styles.container}>
        <Text onPress = {this.backAction} style={styles.text}>Click Back button!</Text>
      </View>
    );
  }
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: "center",
    justifyContent: "center"
  },
  text: {
    fontSize: 18,
    fontWeight: "bold"
  }
});

export default App;

如果您尝试退出应用程序,请使用

BackHandler.exitApp()

阅读文档

import {BackHandler,Alert} from 'react-native';
const backAction = () => {
    Alert.alert('AppName', 'Are you sure you want to exit?', [
      {
        text: 'NO',
        onPress: () => null,
        style: 'cancel',
      },
      {text: 'YES', onPress: () => BackHandler.exitApp()},
    ]);
    return true;
  };

useEffect(() => {
    BackHandler.addEventListener('hardwareBackPress', backAction);
    return () => {
      BackHandler.removeEventListener('hardwareBackPress', backAction);
    };
  }, []);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM