一、自定义构建函数 @Builder
1、全局
(1)定义
- 定义:全局需要
function
@Builder function 函数名(){ }
- 示例代码中有传参,根据实际需要调整
@Builder function ItemCard(item: Item){
Row({space: 10}){
Image(item.image)
.width(100)
Column({space: 4}){
...
}
.height('100%')
.alignItems(HorizontalAlign.Start)
}
.width('100%')
.backgroundColor('#FFF')
.borderRadius(20)
.height(120)
.padding(10)
}
(2)使用
List({space: 8}){
ForEach(
this.items,
(item: Item) => {
ListItem(){
ItemCard(item)
}
}
)
}
2、局部
(1)定义
- 局部不需要
function
@Builder 函数名(){ }
- 示例代码中有传参,根据实际需要调整
@Builder ItemCard(item: Item){
Row({space: 10}){
Image(item.image)
.width(100)
Column({space: 4}){
...
}
.height('100%')
.alignItems(HorizontalAlign.Start)
}
.width('100%')
.backgroundColor('#FFF')
.borderRadius(20)
.height(120)
.padding(10)
}
(2)使用
List({space: 8}){
ForEach(
this.items,
(item: Item) => {
ListItem(){
this.ItemCard(item)
}
}
)
}
二、公共样式函数
1、全局:@Styles 仅可封装组件通用属性
(1)定义
- 定义:全局需要
function
@Styles function 函数名((){ }
- 仅可封装组件通用属性
@Styles function fillScreen(){
.width('100%')
.height('100%')
.backgroundColor('#EFEFEF')
.padding(20)
}
(2)使用
Column({ space: 8 }) {
...
}
.fillScreen()
2、局部:@Styles 仅可封装组件通用属性
(1)定义
- 局部不需要
function
@Styles 函数名((){ }
- 仅可封装组件通用属性
@Styles fillScreen(){
.width('100%')
.height('100%')
.backgroundColor('#EFEFEF')
.padding(20)
}
(2)使用
Column({ space: 8 }) {
...
}
.fillScreen()
3、设置组件特有属性:@Extend 继承模式,只能写在全局,
(1)定义
@Extend(组件名) function 函数名() {
@Extend(Text) function priceText() {
.fontColor('#F36')
.fontSize(18)
}
(2)使用
Text('补贴:¥' + item.discount)
.priceText()