BackHandler
Backhandler API 检测用于后退导航的硬件按钮按下情况,允许你注册系统后退操作的事件监听器,并允许你控制应用的响应方式。它仅适用于 Android。
¥The Backhandler API detects hardware button presses for back navigation, lets you register event listeners for the system's back action, and lets you control how your application responds. It is Android-only.
事件订阅以相反的顺序调用(即首先调用最后注册的订阅)。
¥The event subscriptions are called in reverse order (i.e. the last registered subscription is called first).
-
如果一个订阅返回 true,那么之前注册的订阅将不会被调用。
¥If one subscription returns true, then subscriptions registered earlier will not be called.
-
如果没有订阅返回 true 或没有注册,它将以编程方式调用默认后退按钮功能来退出应用。
¥If no subscription returns true or none are registered, it programmatically invokes the default back button functionality to exit the app.
对模态用户的警告:如果你的应用显示打开的
Modal
,BackHandler
将不会发布任何事件 (请参阅Modal
文档)。¥Warning for modal users: If your app shows an opened
Modal
,BackHandler
will not publish any events (seeModal
docs).
模式
¥Pattern
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;
});
示例
¥Example
以下示例实现了你确认用户是否要退出应用的场景:
¥The following example implements a scenario where you confirm if the user wants to exit the app:
BackHandler.addEventListener
创建一个事件监听器并返回一个 NativeEventSubscription
对象,应使用 NativeEventSubscription.remove
方法清除该对象。
¥BackHandler.addEventListener
creates an event listener & returns a NativeEventSubscription
object which should be cleared using NativeEventSubscription.remove
method.
与 React 导航一起使用
¥Usage with React Navigation
如果你使用 React Navigation 跨不同屏幕导航,你可以按照 自定义 Android 后退按钮行为 上的指南进行操作
¥If you are using React Navigation to navigate across different screens, you can follow their guide on Custom Android back button behaviour
后处理机钩
¥Backhandler hook
React Native 钩子 有一个很好的 useBackHandler
钩子,它将简化设置事件监听器的过程。
¥React Native Hooks has a nice useBackHandler
hook which will simplify the process of setting up event listeners.
参考
¥Reference
方法
¥Methods
addEventListener()
static addEventListener(
eventName: BackPressEventName,
handler: () => boolean | null | undefined,
): NativeEventSubscription;
exitApp()
static exitApp();
removeEventListener()
static removeEventListener(
eventName: BackPressEventName,
handler: () => boolean | null | undefined,
);