• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Dynamic UI Element Building
2
3After you've created a custom component (as described in [Basic UI Description](arkts-basic-ui-description.md)), you can customize the internal UI structure for the component, by drawing on the capability of dynamic UI element building.
4
5## @Builder
6
7The **@Builder** decorator is used to decorate a function for quickly generating multiple layouts in a custom component. This function can be declared outside the **build** function and used in the **build** function or other **@Builder** decorated functions. The following example shows how to use **@Builder**.
8
9```ts
10// xxx.ets
11@Component
12struct CompB {
13  @State CompValue: string = ''
14
15  aboutToAppear() {
16    console.info('CompB aboutToAppear.')
17  }
18
19  aboutToDisappear() {
20    console.info('CompB aboutToDisappear.')
21  }
22
23  build() {
24    Column() {
25      Button(this.CompValue)
26        .margin(5)
27    }
28  }
29}
30
31@Entry
32@Component
33struct CompA {
34  size1: number = 100
35  @State CompValue1: string = "Hello,CompValue1"
36  @State CompValue2: string = "Hello,CompValue2"
37  @State CompValue3: string = "Hello,CompValue3"
38
39  // Use the custom component CompB in the @Builder decorated function CompC.
40  @Builder CompC(value: string) {
41    CompB({ CompValue: value })
42  }
43
44  @Builder SquareText(label: string) {
45    Text(label)
46      .fontSize(18)
47      .width(1 * this.size1)
48      .height(1 * this.size1)
49  }
50
51  // Use the @Builder decorated function SquareText in the @Builder decorated function RowOfSquareTexts.
52  @Builder RowOfSquareTexts(label1: string, label2: string) {
53    Row() {
54      this.SquareText(label1)
55      this.SquareText(label2)
56    }
57    .width(2 * this.size1)
58    .height(1 * this.size1)
59  }
60
61  build() {
62    Column() {
63      Row() {
64        this.SquareText("A")
65        this.SquareText("B")
66      }
67      .width(2 * this.size1)
68      .height(1 * this.size1)
69
70      this.RowOfSquareTexts("C", "D")
71      Column() {
72        // Use the @Builder decorated custom components three times.
73        this.CompC(this.CompValue1)
74        this.CompC(this.CompValue2)
75        this.CompC(this.CompValue3)
76      }
77      .width(2 * this.size1)
78      .height(2 * this.size1)
79    }
80    .width(2 * this.size1)
81    .height(2 * this.size1)
82  }
83}
84```
85![builder](figures/builder.PNG)
86
87## @BuilderParam<sup>8+</sup>
88
89The **@BuilderParam** decorator is used to decorate the function type attributes (for example, **@BuilderParam noParam: () => void**) in a custom component. When the custom component is initialized, the attributes decorated by **@BuilderParam** must be assigned values.
90
91### Background
92
93In certain circumstances, you may need to add a specific function, such as a click-to-jump action, to a custom component. However, embedding an event method directly inside of the component will add the function to all places where the component is imported. This is where the **@BuilderParam** decorator comes into the picture. When initializing a custom component, you can assign a **@Builder** decorated method to the **@BuilderParam** decorated attribute, thereby adding the specific function to the custom component.
94
95### Component Initialization Through Parameters
96
97When initializing a custom component through parameters, assign a **@Builder** decorated method to the **@BuilderParam** decorated attribute — **content**, and call the value of **content** in the custom component. If no parameter is passed when assigning a value to the **@BuilderParam** decorated attribute (for example, **noParam: this.specificNoParam**), define the type of the attribute as a function without a return value (for example, **@BuilderParam noParam: () => void**). If any parameter is passed when assigning a value to the **@BuilderParam** decorated attribute (for example, **withParam: this.SpecificWithParam('WithParamA')**), define the type of the attribute as **any** (for example, **@BuilderParam withParam: any**).
98
99```ts
100// xxx.ets
101@Component
102struct CustomContainer {
103  header: string = ''
104  @BuilderParam noParam: () => void
105  @BuilderParam withParam: any
106  footer: string = ''
107
108  build() {
109    Column() {
110      Text(this.header)
111        .fontSize(30)
112      this.noParam()
113      this.withParam()
114      Text(this.footer)
115        .fontSize(30)
116    }
117  }
118}
119
120@Entry
121@Component
122struct CustomContainerUser {
123  @Builder specificNoParam() {
124    Column() {
125      Text('noParam').fontSize(30)
126    }
127  }
128
129  @Builder SpecificWithParam(label: string) {
130    Column() {
131      Text(label).fontSize(30)
132    }
133  }
134
135  build() {
136    Column() {
137      CustomContainer({
138        header: 'HeaderA',
139        noParam: this.specificNoParam,
140        withParam: this.SpecificWithParam('WithParamA'),
141        footer: 'FooterA'
142      })
143      Divider()
144        .strokeWidth(3)
145        .margin(10)
146      CustomContainer({
147        header: 'HeaderB',
148        noParam: this.specificNoParam,
149        withParam: this.SpecificWithParam('WithParamB'),
150        footer: 'FooterB'
151      })
152    }
153  }
154}
155```
156
157![builder1](figures/builder1.PNG)
158
159### Component Initialization Through Trailing Closure
160
161In a custom component, the **@BuilderParam** decorated attribute can be initialized using a trailing closure. During initialization, the component name is followed by a pair of braces ({}) to form a trailing closure (**CustomContainer(){}**). You can consider a trailing closure as a container and add content to it. For example, you can add a component (**{Column(){...}**) to the closure. The syntax of the closure is the same as that of **build**. In this scenario, the custom component has one and only one **@BuilderParam** decorated attribute.
162
163Example: Add a **\<Column>** component and a click event to the closure, and call the **specificParam** method decorated by **@Builder** in the new **\<Column>** component. After the **\<Column>** component is clicked, the value of the **CustomContainer** component's **header** attribute will change from **header** to **changeHeader**. When the component is initialized, the content of the trailing closure will be assigned to the **closer** attribute decorated by **@BuilderParam**.
164
165```ts
166// xxx.ets
167@Component
168struct CustomContainer {
169  header: string = ''
170  @BuilderParam closer: () => void
171
172  build() {
173    Column() {
174      Text(this.header)
175        .fontSize(30)
176      this.closer()
177    }
178  }
179}
180
181@Builder function specificParam(label1: string, label2: string) {
182  Column() {
183    Text(label1)
184      .fontSize(30)
185    Text(label2)
186      .fontSize(30)
187  }
188}
189
190@Entry
191@Component
192struct CustomContainerUser {
193  @State text: string = 'header'
194
195  build() {
196    Column() {
197      CustomContainer({
198        header: this.text,
199      }) {
200        Column() {
201          specificParam('testA', 'testB')
202        }.backgroundColor(Color.Yellow)
203        .onClick(() => {
204          this.text = 'changeHeader'
205        })
206      }
207    }
208  }
209}
210```
211
212![builder2](figures/builder2.gif)
213
214## @Styles
215
216The **@Styles** decorator helps avoid repeated style setting, by extracting multiple style settings into one method. When declaring a component, you can invoke this method and use the **@Styles** decorator to quickly define and reuse the custom styles of a component. **@Styles** supports only universal attributes.
217
218**@Styles** can be defined inside or outside a component declaration. When it is defined outside a component declaration, the component name must be preceded by the keyword **function**.
219
220```ts
221// xxx.ets
222@Styles function globalFancy () {
223  .width(150)
224  .height(100)
225  .backgroundColor(Color.Pink)
226}
227
228@Entry
229@Component
230struct FancyUse {
231  @Styles componentFancy() {
232    .width(100)
233    .height(200)
234    .backgroundColor(Color.Yellow)
235  }
236
237  build() {
238    Column({ space: 10 }) {
239      Text('FancyA')
240        .globalFancy()
241        .fontSize(30)
242      Text('FancyB')
243        .globalFancy()
244        .fontSize(20)
245      Text('FancyC')
246        .componentFancy()
247        .fontSize(30)
248      Text('FancyD')
249        .componentFancy()
250        .fontSize(20)
251    }
252  }
253}
254```
255
256![styles](figures/styles.PNG)
257
258**@Styles** can also be used inside the **[StateStyles](../reference/arkui-ts/ts-universal-attributes-polymorphic-style.md)** attribute declaration of a component, to assign state-specific attributes to the component.
259
260In **StateStyles**, **@Styles** decorated methods defined outside the component can be directly called, while those defined inside can be called only with the keyword **this**.
261
262```ts
263// xxx.ets
264@Styles function globalFancy () {
265  .width(120)
266  .height(120)
267  .backgroundColor(Color.Green)
268}
269
270@Entry
271@Component
272struct FancyUse {
273  @Styles componentFancy() {
274    .width(80)
275    .height(80)
276    .backgroundColor(Color.Red)
277  }
278
279  build() {
280    Row({ space: 10 }) {
281      Button('Fancy')
282        .stateStyles({
283          normal: {
284            .width(100)
285            .height(100)
286            .backgroundColor(Color.Blue)
287          },
288          disabled: this.componentFancy,
289          pressed: globalFancy
290        })
291    }
292  }
293}
294```
295
296![styles1](figures/styles1.gif)
297
298## @Extend
299
300The **@Extend** decorator adds new attribute methods to built-in components, such as **\<Text>**, **\<Column>**, and **\<Button>**. In this way, the built-in components are extended instantly.
301
302```ts
303// xxx.ets
304@Extend(Text) function fancy (fontSize: number) {
305  .fontColor(Color.Red)
306  .fontSize(fontSize)
307  .fontStyle(FontStyle.Italic)
308  .fontWeight(600)
309}
310
311@Entry
312@Component
313struct FancyUse {
314  build() {
315    Row({ space: 10 }) {
316      Text("Fancy")
317        .fancy(16)
318      Text("Fancy")
319        .fancy(24)
320      Text("Fancy")
321        .fancy(32)
322    }
323  }
324}
325
326```
327
328> **NOTE**
329>
330> - The **@Extend** decorator cannot be defined inside the struct of a custom component.
331> - The **@Extend** decorator supports only attribute methods.
332
333![extend](figures/extend.PNG)
334
335## @CustomDialog
336
337The **@CustomDialog** decorator is used to decorate custom dialog boxes, enabling their content and styles to be dynamically set.
338
339```ts
340// xxx.ets
341@CustomDialog
342struct DialogExample {
343  controller: CustomDialogController
344  action: () => void
345
346  build() {
347    Row() {
348      Button('Close CustomDialog')
349        .onClick(() => {
350          this.controller.close()
351          this.action()
352        })
353    }.padding(20)
354  }
355}
356
357@Entry
358@Component
359struct CustomDialogUser {
360  dialogController: CustomDialogController = new CustomDialogController({
361    builder: DialogExample({ action: this.onAccept }),
362    cancel: this.existApp,
363    autoCancel: true
364  });
365
366  onAccept() {
367    console.info('onAccept');
368  }
369
370  existApp() {
371    console.info('Cancel dialog!');
372  }
373
374  build() {
375    Column() {
376      Button('Click to open Dialog')
377        .onClick(() => {
378          this.dialogController.open()
379        })
380    }
381  }
382}
383```
384
385![customdialog](figures/customDialog.gif)
386