DEV Community

ShuGang Zhou
ShuGang Zhou

Posted on

HarmonyOS NEXT 实战系列09-生命周期

Image description

页面生命周期,即被@Entry装饰的组件生命周期,提供以下生命周期接口:

onPageShow:页面每次显示时触发一次,包括路由过程、应用进入前台等场景。
onPageHide:页面每次隐藏时触发一次,包括路由过程、应用进入后台等场景。
onBackPress:当用户点击返回按钮时触发。
aboutToAppear:组件即将出现时回调该接口,具体时机为在创建自定义组件的新实例后,在执行其build()函数之前执行
aboutToDisappear:aboutToDisappear函数在自定义组件析构销毁之前执行。

@Entry
@Component
struct Index {
  aboutToAppear(): void {
    console.log('组件创建')
  }

  aboutToDisappear(): void {
    console.log('组件销毁')
  }

  onPageShow(): void {
    console.log('组件显示')
  }

  onPageHide(): void {
    console.log('组件隐藏')
  }


  build() {
    Column() {

    }
  }
}
Enter fullscreen mode Exit fullscreen mode

组件生命周期,即一般用@Component装饰的自定义组件的生命周期,提供以下生命周期接口:

aboutToAppear:组件即将出现时回调该接口,具体时机为在创建自定义组件的新实例后,在执行其build()函数之前执行
aboutToDisappear:aboutToDisappear函数在自定义组件析构销毁之前执行。

@Component
struct SonCom {
  aboutToAppear(): void {
    console.log('组件创建')
  }

  aboutToDisappear(): void {
    console.log('组件销毁')
  }

  build() {
    Column() {
      Text('我是子组件')
    }
    .width(200)
    .height(200)
    .border({ width: .5 })
  }
}

@Entry
@Component
struct Index {
  @State show: boolean = false

  build() {
    Column() {
      Text('组件的生命周期')
      Button('切换子组件显示')
        .onClick(() => {
          this.show = !this.show
        })
      if (this.show) {
        SonCom()
      }

    }
  }
}

Enter fullscreen mode Exit fullscreen mode

Heroku

Amplify your impact where it matters most — building exceptional apps.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please show some love ❤️ or share a kind word in the comments if you found this useful!

Got it!