目录

Tabs及其子组件生命周期触发问题

问题现象

开发者在处理Tabs组件生命周期时,最常遇到以下几个问题:

背景知识

解决方案

全量代码如下:

import { promptAction } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct TabsLifeCycle {
  @State selectedIndex: number = 0;
  fontColor: string = '#000';
  selectedFontColor: string = '#0A59F7';
  private controller: TabsController = new TabsController();

  @Builder
  tabBuilder(index: number, name: string) {
    Column() {
      Text(name)
        .fontColor(this.selectedIndex === index ? this.selectedFontColor : this.fontColor)
        .fontSize(16)
        .fontWeight(this.selectedIndex === index ? 500 : 400)
        .lineHeight(22);
    }
    .onClick(() => {
      this.controller.changeIndex(index);
      this.selectedIndex = index;
    });
  }

  build() {
    Column() {
      Tabs({ controller: this.controller }) {
        TabContent() {
          Column() {
            Text('onWillShow/onWillHide事件');
          }
          .justifyContent(FlexAlign.Center)
          .width('100%')
          .height('100%');
        }
        .tabBar(this.tabBuilder(0, '首页'))
        // 通过onWillShow
        .onWillShow(() => {
          try {
            this.getUIContext().getPromptAction().showToast({
              message: '首页要出现了',
              duration: 2000,
              showMode: promptAction.ToastShowMode.TOP_MOST,
              bottom: 85
            });
          } catch (error) {
            let message = (error as BusinessError).message;
            let code = (error as BusinessError).code;
            console.error(`showToast args error code is ${code}, message is ${message}`);
          }
        })
        .onWillHide(() => {
          try {
            this.getUIContext().getPromptAction().showToast({
              message: '首页要隐藏了',
              duration: 2000,
              showMode: promptAction.ToastShowMode.TOP_MOST,
              bottom: 85
            });
          } catch (error) {
            let message = (error as BusinessError).message;
            let code = (error as BusinessError).code;
            console.error(`showToast args error code is ${code}, message is ${message}`);
          }
        });
        TabContent() {
          Column()
            .width('100%')
            .height('100%');
        }
        .tabBar(this.tabBuilder(1, '商城'))
        // 通过onVisibleAreaChange实现监控当前页面是否占据了屏幕至少一半的部分
        .onVisibleAreaChange([0.0, 1.0], (isExpanding: boolean, currentRatio: number) => {
          console.info(`Test Text isExpanding: ${isExpanding}, currentRatio: ${currentRatio}`);
          if (isExpanding && currentRatio >= 0.5) {
            try {
              this.getUIContext().getPromptAction().showToast({
                message: '第二页在界面上展示了至少一半的部分',
                duration: 2000,
                showMode: promptAction.ToastShowMode.TOP_MOST,
                bottom: 85
              });
            } catch (error) {
              let message = (error as BusinessError).message;
              let code = (error as BusinessError).code;
              console.error(`showToast args error code is ${code}, message is ${message}`);
            }
            console.info(`Test Text is fully visible. currentRatio: ${currentRatio}`);
          }
        });
        TabContent() {
          Column()
            .width('100%')
            .height('100%');
        }
        .tabBar(this.tabBuilder(2, '我的'));
      }
      .onTabBarClick(() => {
        try {
          this.getUIContext().getPromptAction().showToast({
            message: 'TabBar被点击了',
            duration: 2000,
            showMode: promptAction.ToastShowMode.TOP_MOST,
            bottom: 85
          });
        } catch (error) {
          let message = (error as BusinessError).message;
          let code = (error as BusinessError).code;
          console.error(`showToast args error code is ${code}, message is ${message}`);
        }
      })
      // 使用onChange监听页面切换
      .onChange((index: number) => {
        try {
          this.getUIContext().getPromptAction().showToast({
            message: `监听onChange,当前切换的是第${index + 1}个Tab`,
            duration: 2000,
            showMode: promptAction.ToastShowMode.TOP_MOST,
            bottom: 85
          });
        } catch (error) {
          let message = (error as BusinessError).message;
          let code = (error as BusinessError).code;
          console.error(`showToast args error code is ${code}, message is ${message}`);
        }
      })
      // 使用onAnimationStart监听切换动画开始
      .onAnimationStart((index: number, targetIndex: number) => {
        if (index === targetIndex) {
          return;
        }
        this.selectedIndex = targetIndex;
        try {
          this.getUIContext().getPromptAction().showToast({
            message: `监听onAnimationStart,当前切换掉的是第${index + 1}个Tab,展示的是第${targetIndex + 1}个Tab`,
            duration: 2000,
            showMode: promptAction.ToastShowMode.TOP_MOST,
            bottom: 85
          });
        } catch (error) {
          let message = (error as BusinessError).message;
          let code = (error as BusinessError).code;
          console.error(`showToast args error code is ${code}, message is ${message}`);
        }
      });
    }
    .width('100%')
    .height('100%');
  }
}

总结

Tabs及其子组件生命周期相关问题可以总结成如下表格:

组件

关键生命周期监听事件

功能描述与触发时机

Tabs事件

onChange

最核心的切换事件。当TabContent发生切换(无论是点击TabBar、滑动还是代码控制)时触发,返回切换后的新索引。

onTabBarClick

专门监听TabBar的点击事件。当用户点击TabBar上的某个标签时触发,返回被点击标签的索引。注意:即使点击当前已选中的标签也会触发。

TabContent事件

onWillShow

当对应的TabContent即将显示时触发。在非首次创建的切换场景中,这是子内容“显示”的信号。

onWillHide

当对应的TabContent即将隐藏时触发。是子内容“隐藏”的信号。

通用组件生命周期

aboutToAppear/aboutToDisappear

作为ArkUI组件的通用生命周期,在组件即将出现或消失时触发一次。对于TabContent内的子组件,仅在首次创建、最终销毁时分别触发,后续切换页面不再触发。

页面生命周期

onPageShow/onPageHide

完全不会触发。这些是@Entry页面独有的生命周期,TabContent内的子组件不具备触发该事件的能力。