HarmonyOS 页面及组件的生命周期

71 阅读1分钟

生命周期组件,需要区分页面还是子组件,对应的生命周期函数不一样

@Entry
@Component
struct LifeCyclePage {
  @State message: string = 'Hello World'
  @State flag: boolean = false

  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .onClick(() => {
            this.flag = !this.flag
          })
        if (this.flag) {
          ItemChild()
        }

      }
      .width('100%')
    }
    .height('100%')
  }
  /**
   * 生命周期
   * 页面生命周期
   */
  onPageShow() {
    console.log("onPageShow() 页面显示时")
  }

  onPageHide() {
    console.log("onPageHide() 页面隐藏")
  }

  onBackPress() {
    console.log("onBackPress() 点击返回时")
  }

  //组件生命周期
  aboutToAppear(){
    //所有页面 和 组件 都有(在build{}之前运行)
    console.log("aboutToAppear() 组件即将出现时")
  }

  aboutToDisappear() {
    console.log("aboutToDisappear() 组件不显示时")
  }
}

@Component
struct ItemChild {
  build() {
    Row() {
      Text("子组件")
        .fontSize(20)
        .fontColor(Color.Gray)
    }
  }

  //组件生命周期
  aboutToAppear(){
    //所有页面 和 组件 都有(在build{}之前运行)
    console.log("aboutToAppear() 组件即将出现时")
  }

  aboutToDisappear() {
    console.log("aboutToDisappear() 组件不显示时")
  }
}