文档管理中心

如何在Navigation页面中实现侧滑事件拦截

  1. 因为功能以har形式集成在主工程中,没有@Entry修饰的组件,无法作为入口组件,也不能使用onBackPress生命周期函数。
  2. 在使用onBackPressed时,它是NavDestination的事件,需要与NavDestination组件配合使用。组件本身用于显示导航内容区,作为子页面的根容器。因此,若需拦截子页面的返回事件,可以使用onBackPressed回调。
  3. 在使用onBackPress时, 生命周期函数onBackPress只能在 @Entry 组件中使用,因此可以使用该函数拦截入口组件的返回事件。
  4. 开发者可通过NavDestination组件onBackPressed回调拦截返回事件。

参考代码如下:

收起
自动换行
深色代码主题
复制
  1. import { ShowDialogSuccessResponse } from '@kit.ArkUI';
  2. @Entry
  3. @Component
  4. struct SideslipIntercept {
  5. controller: TextAreaController = new TextAreaController();
  6. @State text: string = '';
  7. @Provide pageStack: NavPathStack = new NavPathStack();
  8. build() {
  9. // Main page uses NavDestination as carrier to display Navigation content area
  10. Navigation(this.pageStack) {
  11. }
  12. .onAppear(() => {
  13. this.pageStack.pushPathByName('MainPage', null, false);
  14. })
  15. // Create NavDestination component, use its onBackPressed callback to intercept back event
  16. .navDestination(this.textArea)
  17. }
  18. @Builder
  19. textArea(name: string) {
  20. NavDestination() {
  21. Column() {
  22. TextArea({
  23. text: this.text,
  24. placeholder: 'input your word...',
  25. controller: this.controller
  26. })
  27. .onChange((value: string) => {
  28. this.text = value;
  29. })
  30. }
  31. .justifyContent(FlexAlign.Start)
  32. .width('100%')
  33. .height('100%')
  34. }
  35. .onBackPressed(() => {
  36. // Interception logic can be added here, then return true to proceed
  37. this.getUIContext().getPromptAction().showDialog({
  38. message: 'Save?',
  39. alignment: DialogAlignment.Center,
  40. buttons: [
  41. {
  42. text: "Don't Save",
  43. color: '#0000FF'
  44. },
  45. {
  46. text: 'Save',
  47. color: '#0000FF'
  48. }
  49. ]
  50. }).then((data: ShowDialogSuccessResponse) => {
  51. // When selecting button index in buttons array, starting from 0, second index is 1
  52. // Click Don't Save button
  53. if (data.index === 0) {
  54. console.info('Not saving')
  55. }
  56. // Click Save button
  57. if (data.index === 1) {
  58. console.info('Saving')
  59. }
  60. })
  61. return true;
  62. })
  63. }
  64. }

参考链接

侧滑返回事件拦截案例