1 如何自定义组件
通过Component修饰实现一个struct CustomComponents定义即可。
- 代码示例:
@Entry
@Component
struct CustomComponents {
build() {
Row() {
Column() {
Text("菜谱选择")
.fontSize(50)
.fontWeight(FontWeight.Bold)
ItemComponentAction()
ItemComponentAction({value:"葱包烩"})
ItemComponentAction({value:"红烧鱼"})
ItemComponentAction({value:"番茄捞面"})
}
.width('100%')
}
.height('100%')
}
}
@Component
struct ItemComponentAction {
//自定义组件中所有成员,都是private属性
value: string = "把子肉"
//@State 是状态机制的修改,通过它自动刷新build方法中需要更新的内容
@State isOk: boolean = false
build() {
//根组件只能有一个
Row() {
Image(this.isOk ? $r('app.media.todo_ok') : $r('app.media.todo_default'))
.width(20)
.height(20)
.margin(10)
Text(this.value)
.decoration({ type: this.isOk ? TextDecorationType.Underline : TextDecorationType.None })
}
.backgroundColor(Color.Yellow)
.borderRadius(25)
.margin({
top: 20,
left: 20,
right: 20
})
.onClick(() => {
this.isOk = !this.isOk
})
}
}
2 自定义组件规则的总结
- 1)组件必须用 @Component修饰
- 2)@Entry修饰了应用执行的入口的组件
- 3)在build方法里面必须有一个根容器,如Row,Column组件
- 4)所有的自定义组件的build方法中,必须只能有一个根组件。如Image('') 和Text()是两个不同的根组件,这里只能放一个