这篇文章介绍一个装饰器 @Styles
他的主要作用是: 当多个组件都有相同的样式,如果每个组件单独设置,会造成大量重复的代码冗余。这时我们可以使用 @Styles
将这些相同样式封装成一个方法,供这些组件调用,达到复用样式的目的
使用方法
@Styles
使用分为两种情况,在组件内使用 或 在全局使用。定义在组件内,作用域就是这个组件,定义在全局,作用域就是这个 .ets
文件
组件内使用
我们先看下面的一个例子,页面上画了两个方块,分别设置了宽、高、背景颜色等:
typescript
@Entry
@Component
struct Index {
build() {
Column() {
Text('方块1号')
.width('50%')
.height(100)
.margin({ top: 20 })
.backgroundColor('#ff04add7')
.fontSize(20)
.textAlign(TextAlign.Center)
Text('方块2号')
.width('50%')
.height(100)
.margin({ top: 20 })
.backgroundColor('#ff04add7')
.fontSize(20)
.textAlign(TextAlign.Center)
}
.width('100%')
}
}
![](https://img2023.cnblogs.com/blog/1289125/202502/1289125-20250207105815545-587212910.png)
在这个例子中,两个 Text
的宽、高样式都是一样的,可以使用 @Styles
将这些样式抽离,做成公共样式,如下:
typescript
@Entry
@Component
struct Index {
build() {
Column() {
Text('方块1号')
.TextStyle()
.fontSize(20)
.textAlign(TextAlign.Center)
Text('方块2号')
.TextStyle()
.fontSize(20)
.textAlign(TextAlign.Center)
}
.width('100%')
}
@Styles
TextStyle() {
.width('50%')
.height(100)
.margin({ top: 20 })
.backgroundColor('#ff04add7')
}
}
注意事项: 通过阅读代码发现,类似 fontSize
、textAlign
等属性没有抽离出来,是因为 @Styles
仅支持
通用属性
fontSize
对文本组件有效,非文本组件,像Image
组件就不需要该属性。TextAlign
也是同理,不是所有组件都支持该属性
作用域: 在组件内定义的 @Styles
只能作用于当前组件
全局使用
@Styles
可以定义在组件内,也可以定义在全局。在全局定义需要加 Function
关键字,组件内定义不需要
typescript
@Entry
@Component
struct Index {
build(){
Column() {
Text('方块1')
.blockStyle()
.textAlign(TextAlign.Center)
.backgroundColor('#ff34e5df')
Text('方块2')
.blockStyle()
.textAlign(TextAlign.Center)
.backgroundColor('#ff3b77de')
Text('方块3')
.blockStyle()
.textAlign(TextAlign.Center)
.backgroundColor('#ff06f566')
}
.width('100%')
}
}
@Styles function blockStyle(){
.width('30%')
.height(100)
}
作用域: 在全局定义的 @Styles
作用于整个 .ets
文件
使用 this
定义在组件内的 @Styles
可以通过 this
访问组件内的常量和状态变量,并可以在 @Styles
方法中通过事件来改变状态变量的值,如下:
typescript
@Entry
@Component
struct Index {
@State heightValue: number = 100
build() {
Text('方块')
.TextStyle()
.textAlign(TextAlign.Center)
}
@Styles
TextStyle(){
.width('50%')
.height(this.heightValue)
.backgroundColor('#e1e1e1')
.onClick(() => {
this.heightValue = 200
})
}
}
效果如下:
![](https://img2023.cnblogs.com/blog/1289125/202502/1289125-20250207105816072-837850158.gif)
注意事项: 在 @Styles
中使用的事件,只支持
通用事件
不支持传参
![](https://img2023.cnblogs.com/blog/1289125/202502/1289125-20250207105816485-775336359.png)
总结
@Styles
可以在组件内或全局进行定义,全局定义时需要在方法名前面添加function
关键字,组件内定义则不需要- 访问this :组件内的
@Styles
可以通过this
访问组件的常量和状态变量,并可以在@Styles
方法内部通过事件来改变状态变量的值 - 优先级 :组件内的
@Styles
优先级高于 全局@Styles
。框架优先找当前组件内的@Styles
,如果找不到,则会全局查找 - 作用域 :组件内的
@Styles
只能在当前组件使用,全局的@Styles
只能在当前.ets
文件中使用,不支持export
一些弊端:
最后
如果大家有不理解的地方可以留言,或自行阅读文档 文档地址