• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# 自定义组件的生命周期
2
3自定义组件的生命周期回调函数用于通知用户该自定义组件的生命周期,这些回调函数是私有的,在运行时由开发框架在特定的时间进行调用,不能从应用程序中手动调用这些回调函数。
4
5> **说明:**
6>
7> - 允许在生命周期函数中使用Promise和异步回调函数,比如网络资源获取,定时器设置等;
8>
9> - 不允许在生命周期函数中使用async await。
10
11
12## aboutToAppear
13
14aboutToAppear?(): void
15
16aboutToAppear函数在创建自定义组件的新实例后,在执行其build函数之前执行。允许在aboutToAppear函数中改变状态变量,更改将在后续执行build函数中生效。
17
18从API version 9开始,该接口支持在ArkTS卡片中使用。
19
20## aboutToDisappear
21
22aboutToDisappear?(): void
23
24aboutToDisappear函数在自定义组件析构销毁之前执行。不允许在aboutToDisappear函数中改变状态变量,特别是@Link变量的修改可能会导致应用程序行为不稳定。
25
26从API version 9开始,该接口支持在ArkTS卡片中使用。
27
28**示例1:**
29
30```ts
31// xxx.ets
32@Entry
33@Component
34struct CountDownTimerComponent {
35  @State countDownFrom: number = 10
36  private timerId: number = -1
37
38  aboutToAppear(): void {
39    this.timerId = setInterval(() => {
40      if (this.countDownFrom <= 1) {
41        clearTimeout(this.timerId)  // countDownFrom小于等于1时清除计时器
42      }
43      this.countDownFrom -= 1
44    }, 1000) // countDownFrom每1s减1
45  }
46
47  aboutToDisappear(): void {
48    if (this.timerId > 0) {
49      clearTimeout(this.timerId)
50      this.timerId = -1
51    }
52  }
53
54  build() {
55    Column() {
56      Text(`${this.countDownFrom} sec left`)
57        .fontSize(30)
58        .margin(30)
59    }.width('100%')
60  }
61}
62```
63
64![aboutToAppear](figures/aboutToAppear.gif)
65
66上述示例表明,生命周期函数对于允许CountDownTimerComponent管理其计时器资源至关重要,类似的函数也包括异步从网络请求加载资源。
67
68## onPageShow
69
70onPageShow?(): void
71
72页面每次显示时触发一次,包括路由过程、应用进入前后台等场景,仅@Entry修饰的自定义组件生效。
73
74## onPageHide
75
76onPageHide?(): void
77
78页面每次隐藏时触发一次,包括路由过程、应用进入前后台等场景,仅@Entry修饰的自定义组件生效。
79
80## onBackPress
81
82onBackPress?(): void
83
84当用户点击返回按钮时触发,仅@Entry修饰的自定义组件生效。返回true表示页面自己处理返回逻辑,不进行页面路由,返回false表示使用默认的路由返回逻辑。不设置返回值按照false处理。
85
86**示例2:**
87
88```ts
89// xxx.ets
90@Entry
91@Component
92struct IndexComponent {
93  @State textColor: Color = Color.Black
94
95  onPageShow() {
96    this.textColor = Color.Blue
97    console.info('IndexComponent onPageShow')
98  }
99
100  onPageHide() {
101    this.textColor = Color.Transparent
102    console.info('IndexComponent onPageHide')
103  }
104
105  onBackPress() {
106    this.textColor = Color.Red
107    console.info('IndexComponent onBackPress')
108  }
109
110  build() {
111    Column() {
112      Text('Hello World')
113        .fontColor(this.textColor)
114        .fontSize(30)
115        .margin(30)
116    }.width('100%')
117  }
118}
119```
120
121![lifecycle](figures/lifecycle.PNG)
122
123## onLayout<sup>9+</sup>
124
125onLayout?(children: Array\<LayoutChild\>, constraint: ConstraintSizeOptions): void
126
127框架会在自定义组件布局时,将该自定义组件的子节点信息和自身的尺寸范围通过onLayout传递给该自定义组件。不允许在onLayout函数中改变状态变量。
128
129该接口支持在ArkTS卡片中使用。
130
131**参数:**
132
133| 参数名     | 类型                                                                             | 说明                   |
134| ---------- | -------------------------------------------------------------------------------- | ---------------------- |
135| children   | Array\<[LayoutChild](#layoutchild9)\>                                            | 子组件布局信息。       |
136| constraint | [ConstraintSizeOptions](../reference/arkui-ts/ts-types.md#constraintsizeoptions) | 父组件constraint信息。 |
137
138## onMeasure<sup>9+</sup>
139
140onMeasure?(children: Array\<LayoutChild\>, constraint: ConstraintSizeOptions): void
141
142框架会在自定义组件确定尺寸时,将该自定义组件的子节点信息和自身的尺寸范围通过onMeasure传递给该自定义组件。不允许在onMeasure函数中改变状态变量。
143
144该接口支持在ArkTS卡片中使用。
145
146**参数:**
147
148| 参数名     | 类型                                                                             | 说明                   |
149| ---------- | -------------------------------------------------------------------------------- | ---------------------- |
150| children   | Array\<[LayoutChild](#layoutchild9)\>                                            | 子组件布局信息。       |
151| constraint | [ConstraintSizeOptions](../reference/arkui-ts/ts-types.md#constraintsizeoptions) | 父组件constraint信息。 |
152
153## LayoutChild<sup>9+</sup>
154
155子组件布局信息。
156
157该接口支持在ArkTS卡片中使用。
158
159| 参数       | 参数类型                                                                                                    | 描述                                   |
160| ---------- | ----------------------------------------------------------------------------------------------------------- | -------------------------------------- |
161| name       | string                                                                                                      | 子组件名称。                           |
162| id         | string                                                                                                      | 子组件id。                             |
163| constraint | [ConstraintSizeOptions](../reference/arkui-ts/ts-types.md#constraintsizeoptions)                            | 子组件约束尺寸。                       |
164| borderInfo | [LayoutBorderInfo](#layoutborderinfo9)                                                                      | 子组件border信息。                     |
165| position   | [Position](../reference/arkui-ts/ts-types.md#position)                                                      | 子组件位置坐标。                       |
166| measure    | (childConstraint: [ConstraintSizeOptions](../reference/arkui-ts/ts-types.md#constraintsizeoptions)) => void | 调用此方法对子组件的尺寸范围进行限制。 |
167| layout     | (LayoutInfo: [LayoutInfo](#layoutinfo9)) => void                                                           | 调用此方法对子组件的位置信息进行限制。 |
168
169## LayoutBorderInfo<sup>9+</sup>
170
171子组件border信息。
172
173该接口支持在ArkTS卡片中使用。
174
175| 参数        | 参数类型                                                   | 描述                                           |
176| ----------- | ---------------------------------------------------------- | ---------------------------------------------- |
177| borderWidth | [EdgeWidths](../reference/arkui-ts/ts-types.md#edgewidths) | 边框宽度类型,用于描述组件边框不同方向的宽度。 |
178| margin      | [Margin](../reference/arkui-ts/ts-types.md#margin)         | 外边距类型,用于描述组件不同方向的外边距。     |
179| padding     | [Padding](../reference/arkui-ts/ts-types.md#padding)       | 内边距类型,用于描述组件不同方向的内边距。     |
180
181## LayoutInfo<sup>9+</sup>
182
183子组件layout信息。
184
185该接口支持在ArkTS卡片中使用。
186
187| 参数       | 参数类型                                                                         | 描述             |
188| ---------- | -------------------------------------------------------------------------------- | ---------------- |
189| position   | [Position](../reference/arkui-ts/ts-types.md#position)                           | 子组件位置坐标。 |
190| constraint | [ConstraintSizeOptions](../reference/arkui-ts/ts-types.md#constraintsizeoptions) | 子组件约束尺寸。 |
191
192**示例3:**
193
194```ts
195// xxx.ets
196@Entry
197@Component
198struct Index {
199  build() {
200    Column() {
201      CustomLayout() {
202        ForEach([1, 2, 3], (index) => {
203          Text('Sub' + index)
204            .fontSize(30)
205            .borderWidth(2)
206        })
207      }
208    }
209  }
210}
211
212
213@Component
214struct CustomLayout {
215  @BuilderParam builder: () => {}
216
217  onLayout(children: Array<LayoutChild>, constraint: ConstraintSizeOptions) {
218    let pos = 0
219    children.forEach((child) => {
220      child.layout({ position: { x: pos, y: pos }, constraint: constraint })
221      pos += 100
222    })
223  }
224
225  onMeasure(children: Array<LayoutChild>, constraint: ConstraintSizeOptions) {
226    let size = 100
227    children.forEach((child) => {
228      child.measure({ minHeight: size, minWidth: size, maxWidth: size, maxHeight: size })
229      size += 50
230    })
231  }
232
233  build() {
234    this.builder()
235  }
236}
237```
238
239![customlayout](figures/customLayout.png)
240