メインコンテンツへスキップ

BackHandler

Backhandler APIは、バックナビゲーションのためのハードウェアボタンの押下を検出し、システムのバックアクションのイベントリスナーを登録し、アプリケーションの応答方法を制御できます。これはAndroidのみです。

イベントサブスクリプションは逆順で呼び出されます(つまり、最後に登録されたサブスクリプションが最初に呼び出されます)。

  • いずれかのサブスクリプションがtrueを返した場合、それよりも前に登録されたサブスクリプションは呼び出されません。
  • どのサブスクリプションもtrueを返さないか、何も登録されていない場合、プログラムでデフォルトのバックボタン機能を呼び出してアプリを終了します。

モーダルユーザーへの警告:アプリがModalを開いて表示している場合、BackHandlerはイベントを発行しません(Modalのドキュメントを参照)。

パターン

BackHandler.addEventListener('hardwareBackPress', function () {
/**
* this.onMainScreen and this.goBack are just examples,
* you need to use your own implementation here.
*
* Typically you would use the navigator here to go to the last state.
*/

if (!this.onMainScreen()) {
this.goBack();
/**
* When true is returned the event will not be bubbled up
* & no other back action will execute
*/
return true;
}
/**
* Returning false will let the event to bubble up & let other event listeners
* or the system's default back action to be executed.
*/
return false;
});

次の例では、ユーザーがアプリを終了するかどうかを確認するシナリオを実装しています。

BackHandler.addEventListenerはイベントリスナーを作成し、NativeEventSubscriptionオブジェクトを返します。このオブジェクトは、NativeEventSubscription.removeメソッドを使用してクリアする必要があります。

React Navigationでの使用法

React Navigationを使用して異なる画面間をナビゲートしている場合は、Androidのバックボタンのカスタム動作に関するガイドに従うことができます。

Backhandlerフック

React Native Hooksには、イベントリスナーの設定プロセスを簡素化する便利なuseBackHandlerフックがあります。


リファレンス

メソッド

addEventListener()

static addEventListener(
eventName: BackPressEventName,
handler: () => boolean | null | undefined,
): NativeEventSubscription;

exitApp()

static exitApp();

removeEventListener()

static removeEventListener(
eventName: BackPressEventName,
handler: () => boolean | null | undefined,
);