• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Custom Component Lifecycle
2
3The lifecycle callbacks of a custom component are used to notify users of the lifecycle of the component. These callbacks are private and are invoked by the development framework at a specified time at runtime. They cannot be manually invoked from applications.
4
5>**NOTE**
6>
7>- The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
8>- Promise and asynchronous callback functions can be used in lifecycle functions, for example, network resource getters and timer setters.
9
10
11## aboutToAppear
12
13aboutToAppear?(): void
14
15Invoked after a new instance of the custom component is created and before its **build** function is executed. You can change state variables in the **aboutToAppear** function. The change will take effect when you execute the **build** function next time.
16
17Since API version 9, this API is supported in ArkTS widgets.
18
19## aboutToDisappear
20
21aboutToDisappear?(): void
22
23Invoked before the destructor of the custom component is consumed. Do not change state variables in the **aboutToDisappear** function as doing this can cause unexpected errors. For example, the modification of the **@Link** decorated variable may cause unstable application running.
24
25Since API version 9, this API is supported in ArkTS widgets.
26
27## onPageShow
28
29onPageShow?(): void
30
31Invoked when a page is displayed. This callback is used in the routing process or scenarios where the application is switched to the foreground or background. It works only for the custom components decorated by **@Entry**.
32
33
34## onPageHide
35
36onPageHide?(): void
37
38Invoked when a page is hidden. This callback is used in the routing process or scenarios where the application is switched to the foreground or background. It works only for the custom components decorated by **@Entry**.
39
40
41## onBackPress
42
43onBackPress?(): void | boolean
44
45Invoked when a user clicks the back button. It works only for the custom components decorated by **@Entry**.
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
81![en-us_image_0000001563060749](figures/en-us_image_0000001563060749.png)
82
83
84## onLayout<sup>9+</sup>
85
86onLayout?(children: Array&lt;LayoutChild&gt;, constraint: ConstraintSizeOptions): void
87
88Invoked when the custom component lays out its child components. Through this callback the component receives its child component layout information and size constraint from the framework. The state variable cannot be changed in the **onLayout** callback.
89
90Since API version 9, this API is supported in ArkTS widgets.
91
92**Parameters**
93
94| Name       | Type                                      | Description              |
95| ---------- | ---------------------------------------- | ---------------- |
96| children   | Array&lt;[LayoutChild](#layoutchild9)&gt; | Child component layout information.        |
97| constraint | [ConstraintSizeOptions](ts-types.md#constraintsizeoptions) | Size constraint information of the parent component.|
98
99
100## onMeasure<sup>9+</sup>
101
102onMeasure?(children: Array&lt;LayoutChild&gt;, constraint: ConstraintSizeOptions): void
103
104Invoked when the custom component lays out its child components. Through this callback the component receives its child component layout information and size constraint from the framework. The state variable cannot be changed in the **onMeasure** callback.
105
106Since API version 9, this API is supported in ArkTS widgets.
107
108**Parameters**
109
110| Name       | Type                                      | Description              |
111| ---------- | ---------------------------------------- | ---------------- |
112| children   | Array&lt;[LayoutChild](#layoutchild9)&gt; | Child component layout information.        |
113| constraint | [ConstraintSizeOptions](ts-types.md#constraintsizeoptions) | Size constraint information of the parent component.|
114
115## aboutToReuse<sup>10+</sup>
116
117aboutToReuse?(params: { [key: string]: unknown }): void
118
119Invoked when a custom component previously placed in the cache for future reuse is re-added to the node tree, with the parameters used for constructing the component passed in.
120
121Since API version 10, this API is supported in ArkTS widgets.
122
123**Parameters**
124
125| Name   | Type                        | Description        |
126| ------ | -------------------------- | ---------- |
127| params | { [key: string]: unknown } | Parameters used for constructing the custom component.|
128
129
130```ts
131// xxx.ets
132@Entry
133@Component
134struct Index {
135  @State message: string = 'Hello World'
136  @State switch: boolean = true
137
138  build() {
139    Column() {
140      Button(this.message)
141        .fontSize(50)
142        .fontWeight(FontWeight.Bold)
143        .onClick(() => {
144          this.switch = !this.switch
145        })
146      if (this.switch) {
147        Child()
148      }
149    }
150    .height("100%")
151    .width('100%')
152  }
153}
154
155@Reusable
156@Component
157struct Child {
158  aboutToReuse(params: Object) {
159    console.info("Recycle Child")
160  }
161
162  build() {
163    Column() {
164      Text("Child Component")
165        .fontSize(20)
166    }
167    .borderWidth(2)
168    .height(100)
169  }
170}
171```
172
173## LayoutChild<sup>9+</sup>
174
175Provides the child component layout information.
176
177Since API version 9, this API is supported in ArkTS widgets.
178
179| Parameter        | Type                                    | Description                 |
180| ---------- | ---------------------------------------- | ------------------- |
181| name       | string                                   | Name of the child component.             |
182| id         | string                                   | ID of the child component.             |
183| constraint | [ConstraintSizeOptions](ts-types.md#constraintsizeoptions) | Constraint size of the child component.           |
184| borderInfo | [LayoutBorderInfo](#layoutborderinfo9)   | Provides the border information of the child component.       |
185| position   | [Position](ts-types.md#position8)         | Position coordinates of the child component.           |
186| measure    | (childConstraint:) =&gt; void  | Method called to apply the size constraint to the child component.|
187| layout     | (LayoutInfo:  [LayoutInfo](#layoutinfo9)) =&gt; void| Method called to apply the layout information to the child component.|
188
189
190## LayoutBorderInfo<sup>9+</sup>
191
192Provides the border information of the child component.
193
194Since API version 9, this API is supported in ArkTS widgets.
195
196| Parameter         | Type                                | Description                     |
197| ----------- | ------------------------------------ | ----------------------- |
198| borderWidth | [EdgeWidths](ts-types.md#edgewidths9) | Edge widths in different directions of the component.|
199| margin      | [Margin](ts-types.md#margin)         | Margins in different directions of the component.  |
200| padding     | [Padding](ts-types.md#padding)       | Paddings in different directions of the component.  |
201
202
203## LayoutInfo<sup>9+</sup>
204
205Provides the layout information of the child component.
206
207Since API version 9, this API is supported in ArkTS widgets.
208
209| Parameter        | Type                                    | Description      |
210| ---------- | ---------------------------------------- | -------- |
211| position   | [Position](ts-types.md#position8)         | Position coordinates of the child component.|
212| constraint | [ConstraintSizeOptions](ts-types.md#constraintsizeoptions) | Constraint size of the child component.|
213
214
215```ts
216// xxx.ets
217@Entry
218@Component
219struct Index {
220  build() {
221    Column() {
222      CustomLayout() {
223        ForEach([1, 2, 3], (index: number) => {
224          Text('Sub' + index)
225            .fontSize(30)
226            .borderWidth(2)
227        })
228      }
229    }
230  }
231}
232
233
234@Component
235struct CustomLayout {
236  @Builder
237  doNothingBuilder() {
238  };
239
240  @BuilderParam builder: () => void = this.doNothingBuilder;
241
242  onLayout(children: Array<LayoutChild>, constraint: ConstraintSizeOptions) {
243    let pos = 0;
244    children.forEach((child) => {
245      child.layout({ position: { x: pos, y: pos }, constraint: constraint })
246      pos += 100;
247    })
248  }
249
250  onMeasure(children: Array<LayoutChild>, constraint: ConstraintSizeOptions) {
251    let size = 100;
252    children.forEach((child) => {
253      child.measure({ minHeight: size, minWidth: size, maxWidth: size, maxHeight: size })
254      size += 50;
255    })
256  }
257
258  build() {
259    this.builder()
260  }
261}
262```
263
264![en-us_image_0000001511900496](figures/en-us_image_0000001511900496.png)
265