在我們日常開發(fā)當中是否會經(jīng)常遇到重復樣式,如下圖
image.png
我們可以將樣式封裝成公共樣式崩哩,用@Styles關鍵詞闻察,代碼如下
一、定義公共樣式
將代碼放于文件的最上面
/**
* 全局公共樣式函數(shù)
*/
@Styles function fillScreen(){
.width('100%')
.height('100%')
.backgroundColor('#efefef')
.padding(20)
}
/**
* 全局集成擴展樣式(只能給Text使用)
*/
@Extend(Text) function priceText(fontColor: ResourceColor = '#F36', fontSize: string|number|Resource = 18){
.fontColor(fontColor)
.fontSize(fontSize)
}
這個時候有人要問了琢锋,@Style和@Extend有什么區(qū)別
@Style
只能封裝公共樣式辕漂,就是所有ArkUI組件都具備的樣式屬性,比如width吴超,height等等
@Extend
只能擴展制定ArkUI組件的樣式钉嘹,比如@Extend(Text) 就只能寫Text特有的樣式,@Extend(Image)就只能寫Image特有的樣式鲸阻。
二跋涣、使用公共樣式
//使用fillScreen代碼一
build() {
Row() {
Column({ space: 8 }) {
//代碼略
}
.fillScreen()
}
}
//使用priceText代碼二
Column({ space: 4 }) {
if (item.discount) {
Text(item.name)
Text('原價:¥' + item.price)
.decoration({ type: TextDecorationType.LineThrough })
.priceText('#ccc')
Text('折扣價:¥' + (item.price - item.discount))
.priceText()
Text('補貼:¥' + item.discount)
.priceText()
} else {
Text(item.name)
Text('¥' + item.price)
.priceText()
}
}