使用 BackHandler 和導航屬性處理硬體後退按鈕(不使用已棄用的 BackAndroid 不再使用的導航器)

此示例將向你顯示通常在大多數流程中預期的返回導航。你必須根據預期的行為向每個螢幕新增以下程式碼。有 2 種情況:

  1. 如果堆疊中有超過 1 個螢幕,則裝置後退按鈕將顯示上一個螢幕。
  2. 如果堆疊中只有 1 個螢幕,裝置後退按鈕將退出應用程式。

案例 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;
}

重要提示: 不要忘記在建構函式中繫結方法並刪除 co​​mponentWillUnmount 中的偵聽器。

案例 2:退出應用程式

在這種情況下,無需在該螢幕上處理要退出應用程式的任何內容。

重要提示: 這應該只是堆疊螢幕。