@Component
被@Component修饰,表示该结构体struct是一个自定义组件
特点
可组合
可重用
有生命周期
数据驱动更新
@Component
struct ComponentA {
build() {
Row() {
Column() {
// 重用ComponentB
ComponentB()
Text('first column')
.fontSize(20)
}
Column() {
// 重用ComponentB
ComponentB()
// 和 ComponentC 组合
ComponentC()
Text('second column')
.fontSize(20)
}
}
}
// 生命周期函数
private aboutToAppear() {
console.log('ParentComponent: Just created, about to become rendered first time.')
}
// 生命周期函数
private aboutToDisappear() {
console.log('ParentComponent: about to be removed from the UI.')
}
}
@Entry
被@Entry修饰的组件表面该组件是该源文件的默认显示入口
注:一个源文件最多有且仅有一处@Entry修饰
@Entry
@Component
struct MyComponent {
build() {
Column() {
Text('hello world')
.fontColor(Color.Red)
}
}
}
@Preview
被@Preview修饰表示该组件可以在DevEco开发工具中进行预览
注:一个源文件有且只能设置一处@Preview来装饰一个自定义组件
@Preview
@Component
struct CustomComponent {
build() {
Column() {
Row() {
Text('Hello CustomComponent')
}
}
}
}
@Builder
表示用来定义自定义组件的方法,作用和build函数一样;@Builder类似java中非匿名函数,而组件中默认build函数类似java中匿名函数
@Component
struct CompA {
size : number = 100;
@Builder SquareText(label: string) {
Text(label)
.width(1 * this.size)
.height(1 * this.size)
}
build() {
Column() {
Row() {
this.SquareText("A")
this.SquareText("B")
// or as long as tsc is used
}
}
.width(2 * this.size)
.height(2 * this.size)
}
}
@Extend
表示可以将新的自定义属性添加到内置组件上,方便复用组件的自定义样式;类似AndroidUI中xml中控件相同属性提取style属性复用
注:@Extend装饰器不能定义在struct结构体内。
@Extend(Text) function fancy(fontSize: number) {
.fontColor(Color.Red)
.fontSize(fontSize)
.fontStyle(FontStyle.Italic)
}
@Entry
@Component
struct FancyUse {
build() {
Row({ space: 10 }) {
Text("Fancy")
.fancy(16)
Text("Fancy")
.fancy(24)
}
}
}
@CustomDialog
该装饰器表示用来装饰自定义弹窗。
@CustomDialog
struct CustomDialog {
controller: CustomDialogController;
action: () => void;
build() {
Row() {
Button ("Close CustomDialog")
.onClick(() => {
this.controller.close();
this.action();
})
}.padding(20)
}
}
@Entry
@Component
struct CustomDialogUser {
dialogController : CustomDialogController = new CustomDialogController({
builder: CustomDialog({action: this.onAccept}),
cancel: this.existApp,
autoCancel: true
});
onAccept() {
console.log("onAccept");
}
existApp() {
console.log("Cancel dialog!");
}
build() {
Column() {
Button("Click to open Dialog")
.onClick(() => {
this.dialogController.open()
})
}
}
}



