基于harmonyOS解释自定义组件生命周期
参考原文链接: (developer.huawei.com/consumer/cn…)
自定义组件的生命周期回调函数用于通知用户该自定义组件的生命周期,这些回调函数是私有的,在运行时由开发框架在特定的时间进行调用,不能从应用程序中手动调用这些回调函数。
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%')
}
}
更多生命周期函数请读者自己参考原文。