跳至主内容
版本:0.78

BackHandler

非官方测试版翻译

本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →

BackHandler API 用于检测硬件返回按钮的点击事件,允许注册系统返回操作的事件监听器,并控制应用程序的响应行为。该 API 仅适用于 Android 平台。

事件订阅按反向顺序调用(即最后注册的订阅最先被触发)。

  • 若某个订阅返回 true, 则较早注册的订阅将不会被调用。

  • 若无订阅返回 true 或未注册任何订阅, 系统将通过编程方式触发默认返回按钮功能退出应用。

模态框用户警告: 当应用显示已打开的 Modal 时,BackHandler 不会发布任何事件(参见 Modal 文档)。

实现模式

tsx
const subscription = 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;
},
);

// Unsubscribe the listener on unmount
subscription.remove();

示例

以下示例实现了确认用户是否要退出应用的场景:

BackHandler.addEventListener 创建事件监听器并返回 NativeEventSubscription 对象,应使用 NativeEventSubscription.remove 方法清除该对象。

与 React Navigation 配合使用

若使用 React Navigation 进行跨屏幕导航,请参考其指南:自定义 Android 返回按钮行为

BackHandler 钩子

React Native Hooks 提供了便捷的 useBackHandler 钩子,可简化事件监听器的设置流程。


参考

方法

addEventListener()

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

exitApp()

tsx
static exitApp();