提出问题
当实现 多个 样式相同 的控件 时,需要大量写 重复的样式代码,如下图例子,实现下图效果:
代码如下:
@Entry
@Component
struct ChongyongStyleDemo {
@State message: string = 'Hello World';
build() {
Column() {
Row(){
Text("内容")
.fontSize(20)
}
.width("90%")
.borderRadius(10)
.backgroundColor("#ddd")
.margin({
bottom:4
})
.padding({
top:20,
left:20,
right:20,
bottom:20,
})
Row(){
Text("内容")
.fontSize(20)
}
.width("90%")
.borderRadius(10)
.backgroundColor("#ddd")
.margin({
bottom:4
})
.padding({
top:20,
left:20,
right:20,
bottom:20,
})
Row(){
Text("内容")
.fontSize(20)
}
.width("90%")
.borderRadius(10)
.backgroundColor("#ddd")
.margin({
bottom:4
})
.padding({
top:20,
left:20,
right:20,
bottom:20,
})
}
.height('100%')
.width('100%')
}
}
缺点
每个 Row 的样式代码都相同,如下:
.width("90%")
.borderRadius(10)
.backgroundColor("#ddd")
.margin({
bottom:4
})
.padding({
top:20,
left:20,
right:20,
bottom:20,
})
大量重复代码,一旦需要修改样式,每个 Row 的样式代码 都需要修改,不利于维护
解决
使用 @Styles 装饰器,定义组件重用样式,相当于CSS样式
@Styles介绍
当多个控件有相同的样式时,不必给每个控件编写重复的样式代码,可以用 @Styles 装饰器,将 重复样式 提炼成一个方法,供控件调用
类比:相当于定义 CSS样式,供样式相同的元素使用
定义
@Styles可以定义在 组件内 或 全局
优先级:
组件内 @Styles 的优先级高于全局 @Styles。框架优先找当前组件内的@Styles,如果找不到,则会全局查找。
定义在组件内
组件内定义时则不需要添加 function 关键字
例子
修改上面的代码,增加方法 @Styles rowStyle(),将 Row 样式提取到该方法中,代码如下:
@Styles rowStyle(){
.width("90%")
.borderRadius(10)
.backgroundColor("#ddd")
.margin({
bottom:4
})
.padding({
top:20,
left:20,
right:20,
bottom:20,
})
}
使用,在每个 Row 调用 .rowStyle(),如下:
Row(){
Text("内容")
.fontSize(20)
}
.rowStyle()
Row(){
Text("内容")
.fontSize(20)
}
.rowStyle()
Row(){
Text("内容")
.fontSize(20)
}
.rowStyle()
完整代码
@Entry
@Component
struct ChongyongStyleDemo {
@State message: string = 'Hello World';
build() {
Column() {
Row(){
Text("内容")
.fontSize(20)
}
.rowStyle()
Row(){
Text("内容")
.fontSize(20)
}
.rowStyle()
Row(){
Text("内容")
.fontSize(20)
}
.rowStyle()
}
.height('100%')
.width('100%')
}
@Styles rowStyle(){
.width("90%")
.borderRadius(10)
.backgroundColor("#ddd")
.margin({
bottom:4
})
.padding({
top:20,
left:20,
right:20,
bottom:20,
})
}
}
定义在全局
在全局定义时需在方法名前面添加 function 关键字,其他用法与 定义在组件内 类似
支持通用属性、通用事件
不支持参数
@Styles方法不支持参数,反例如下。
// 反例: @Styles不支持参数
@Styles function globalFancy (value: number) {
.width(value)
}
