UI组件的添加和删除监听

一级目录

我们通过if条件添加组件的时候,是可以通过onAttachonDetachonAppearonDisAppear来监听组件的添加和删除。
在这里插入图片描述

示例代码

// xxx.ets

// xxx.ets
import { promptAction } from '@kit.ArkUI'



struct AppearExample {
   isShow: boolean = true
   changeAppear: string = '点我卸载挂载组件'
  private myText: string = 'Text for onAppear'

  build() {
    Column() {
      Button(this.changeAppear)
        .onClick(() => {
          this.isShow = !this.isShow
        }).margin(15)
      if (this.isShow) {
        Text(this.myText).fontSize(26).fontWeight(FontWeight.Bold)
          .onAttach(() => {
            console.info(`---onDetach shown---`)
            promptAction.showToast({
              message: 'The text is onAttach',
              duration: 2000,
              bottom: 500
            })
          })
          .onDetach(() => {
            console.error(`---onDetach hidden---`)
            promptAction.showToast({
              message: 'The text is hidden',
              duration: 2000,
              bottom: 500
            })
          }).onAppear(()=>{
          console.info(`---onAppear---`)
          promptAction.showToast({
            message: 'The text is onAppear',
            duration: 2000,
            bottom: 500
          })
        }).onDisAppear(()=>{
          console.error(`---onDisAppear---`)
          promptAction.showToast({
            message: 'The text is onDisAppear',
            duration: 2000,
            bottom: 500
          })
        })
      }
    }.padding(30).width('100%')
  }
}

运行日志如下:红色日志是点击按钮后的输出。
在这里插入图片描述
可以发现,当页面渲染时会先调用onDetach,然后调用onAppear;当组件消失后,会先调用onDetach,然后调用onDisappear.

参考资料

挂载卸载事件

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐