基于harmonyOS解释自定义组件生命周期
参考原文链接
https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/ts-custom-component-lifecycle-V5#abouttoappear


         自定义组件的生命周期回调函数用于通知用户该自定义组件的生命周期,这些回调函数是私有的,在运行时由开发框架在特定的时间进行调用,不能从应用程序中手动调用这些回调函数。

aboutToAppear
格式:aboutToAppear?(): void

aboutToAppear函数在创建自定义组件的新实例后,在执行其build()函数之前执行。允许在aboutToAppear函数中改变状态变量,更改将在后续执行build()函数中生效。实现自定义布局的自定义组件的aboutToAppear生命周期在布局过程中触发。

点击查看代码
@Entry
@Component
struct Index {
  @State message: string = '未触发aboutToAppear函数';
  aboutToAppear(): void {
    this.message='已触发aboutToAppear函数'
  }
  click_function(){
    this.message='点击触发click_function函数'
  }
  build() {
    Row() {
      Text(this.message)
        .fontWeight(FontWeight.Bold)
        .fontSize(30)
        .width('80%')
        .onClick(()=>{
          this.click_function()
        })
    }
    .justifyContent(FlexAlign.Center)
    .height('100%')
    .width('100%')
  }
}
在页面开始前触发aboutToAppear()函数,点击后才触发click_function()函数,前者在页面开始前自动触发,后者需要手动调用。因此该函数可用于接收后台传入的数据和嵌套其他函数自动调用。

onPageShow
格式:onPageShow?(): void

页面每次显示时触发一次,包括路由过程、应用进入前台等场景,仅@Entry装饰的自定义组件生效。

点击查看代码
@Entry
@Component
struct Index {
  @State message: string = '未触发aboutToAppear函数';
  onPageShow(): void {
    this.message='已触发onPageShow函数'
  }
  click_function(){
    this.message='点击触发click_function函数'
  }
  build() {
    Row() {
      Text(this.message)
        .fontWeight(FontWeight.Bold)
        .fontSize(30)
        .width('80%')
        .onClick(()=>{
          this.click_function()
        })
    }
    .justifyContent(FlexAlign.Center)
    .height('100%')
    .width('100%')
  }
}
更多生命周期函数请读者自己参考原文。

posted on 2025-03-14 16:08  旋转门123  阅读(53)  评论(0)    收藏  举报