鸿蒙提供了Extend组件,作用是对组件的属性、点击事件的封装,简化代码、方便调用,但是这个组件的缺点是只能封装一种组件,例如只能封装Text或者是Button,不能跨组件使用,如果不同组件有相同的地方、需要使用咋办呢?鸿蒙提供了Style封装,语法格式比Extend简洁,如下:

通过对比Extend会发现,只需要在function之前添加
,在函数实体封装上公共的属性即可,这里封装的属性可以用在Button、Text、Colum、Row容器上,代码如下:
// 1. 全局定义
@Styles function commonStyles () {
.width(100)
.height(100)
}
@Entry
@Component
struct StylesDemo {
@State message: string = '@styles';
@State bgColor: ResourceColor = Color.Gray
// 2. 组件内定义(才能通过this访问到自己的状态)
@Styles setBg() {
.backgroundColor(this.bgColor)
.onClick(() => {
this.bgColor = Color.Green
})
}
build() {
Column({ space: 10 }) {
Text(this.message)
.fontColor(Color.White)
.commonStyles()
.setBg()
Column() {}
.commonStyles()
.setBg()
Button('按钮')
.commonStyles()
.setBg()
}
.width('100%')
.height('100%')
}
}
总结:鸿蒙中组件属性的封装分别是Extend和Style,区别是前者只能封装到指定的组件,例如封装额时候就指定了,指定是啥组件就是啥组件,Style不分组件,不支持传参,任何组件和容器都可以使用,比Extend更灵活,更适合通用的属性


















