仓颉应用开发之——@Builder和@BuilderParam(9)

一 概述

  • @Builder和@BuilderParam用法说明
  • @Builder和@BuilderParam代码示例

二 @Builder和@BuilderParam用法说明

@Builder @BuilderParam
相同 自定义组件UI 自定义组件UI
不同 无占位符 声明slot占位符

三 @Builder和@BuilderParam代码示例

3.1 @Builder示例

1-代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package ohos_app_cangjie_entry

import ohos.base.*
internal import ohos.component.*
internal import ohos.state_manage.*
import ohos.state_macro_manage.*
import ohos_app_cangjie_entry.pages.*
import ohos_app_cangjie_entry.bean.*

@Builder
func f(fontSz: Int64, color: Color) {
Text("hello world").fontSize(fontSz).fontColor(color)
}

@Entry
@Component
class MyView {
func build() {
Column(20) {
f(20, Color.BLUE)
}
}
}

2-效果图

4.2 @BuilderParam

1-代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package ohos_app_cangjie_entry.pages
internal import ohos.base.*
internal import ohos.component.*
internal import ohos.state_manage.*
import ohos.state_macro_manage.*

@Entry
@Component
public class MyView {
@Builder
func f1(): Unit {
f<Int64>(100, 30, color: Color.BLACK)
}

@Builder
func f2(): Unit {
f<String>("hello", 30, color: Color.RED)
}

func build() {
Column(10) {
FrameView(ab: f1, color: Color.GREEN)
FrameView(ab: f2, color: Color.GRAY)
}
}
}

@Component
class FrameView {
@BuilderParam let ab: () -> Unit
let color: Color

func build() {
Column(10) {
ab()
}.backgroundColor(color)
}
}

@Builder
func f<T>(label: T, fontSz: Int64, color!: Color = Color.WHITE): Unit where T <: ToString {
Text("${label}").fontSize(fontSz).fontColor(color)
}

2-效果图

四 参考

  • HarmonyOS Beta5 仓颉—@Builder
  • HarmonyOS Beta5 ArkTS—@BuilderParam装饰器