Page与自定义Components生命周期
自定义组件
自定义组件一般可以用@component,装饰,在结构体里面用build方法定义UI,或者用@builder装饰一个方法,来作为自定义组件的构造方法
而页面page一般用@Entry,和@component结合起来使用
页面生命周期方法:
onPageShow:页面每次显示时触发
onPageHide:页面每次隐藏时触发
onBackPress:当用户点击返回按钮时触发
组件生命周期方法:
aboutToAppear:组件即将出现时回调该接口,在执行Build()函数之前执行
aboutToDisappear:在自定义组件即将销毁时执行
下图展示的是被@Entry装饰的组件(首页)生命周期:
实例:
// Index.ets
import router from '@ohos.router';@Entry
@Component
struct MyComponent {@State showChild: boolean = true;// 只有被@Entry装饰的组件才可以调用页面的生命周期onPageShow() {console.info('Index onPageShow');}// 只有被@Entry装饰的组件才可以调用页面的生命周期onPageHide() {console.info('Index onPageHide');}// 只有被@Entry装饰的组件才可以调用页面的生命周期onBackPress() {console.info('Index onBackPress');}// 组件生命周期aboutToAppear() {console.info('MyComponent aboutToAppear');}// 组件生命周期aboutToDisappear() {console.info('MyComponent aboutToDisappear');}build() {Column() {// this.showChild为true,创建Child子组件,执行Child aboutToAppearif (this.showChild) {Child()}// this.showChild为false,删除Child子组件,执行Child aboutToDisappearButton('create or delete Child').onClick(() => {this.showChild = false;})// push到Page2页面,执行onPageHideButton('push to next page').onClick(() => {router.pushUrl({ url: 'pages/Page2' });})}}
}@Component
struct Child {@State title: string = 'Hello World';// 组件生命周期aboutToDisappear() {console.info('[lifeCycle] Child aboutToDisappear')}// 组件生命周期aboutToAppear() {console.info('[lifeCycle] Child aboutToAppear')}build() {Text(this.title).fontSize(50).onClick(() => {this.title = 'Hello ArkUI';})}
}
@Builder function ABuilder($$: { paramA1: string }) {Row() {Text(`UseStateVarByReference: ${$$.paramA1} `)}
}
@Entry
@Component
struct Parent {@State label: string = 'Hello';build() {Column() {// 在Parent组件中调用ABuilder的时候,将this.label引用传递给ABuilderABuilder({ paramA1: this.label })Button('Click me').onClick(() => {// 点击“Click me”后,UI从“Hello”刷新为“ArkUI”this.label = 'ArkUI';})}}
}