簡體   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