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