ArkTS學習筆記_封裝復用之@Styles裝飾器
- 背景:
在開發中,如果每個組件的樣式都需要單獨設置,就會出現大量代碼在進行重復樣式設置,雖然可以復制粘貼,但為了代碼簡潔性和后續方便維護,給出的思路是:提煉和封裝相同的樣式成方法,方便復用調用,裝飾器@Style孕育而生。 - 作用:
@Styles裝飾器可以將多條樣式設置,提煉成一個方法,直接在組件使用的位置調用即可復用。通過@Styles裝飾器可以快速定義并復用自定義樣式。用于快速定義并復用自定義樣式。
一、@Styles裝飾器使用說明
- 當前@Styles僅支持通用屬性和通用事件。
- @Styles方法不支持參數,反例如下。
@Styles function globalFancy (value: number) {.width(value)
}
- @Styles可以定義在組件內或全局。
在全局定義時需在方法名前面添加function關鍵字,組件內定義時則不需要添加function關鍵字。
@Styles function functionName() { ... }
@Component
struct FancyUse {@Styles fancy() {.height(100)}}
- 定義在組件內的@Styles可以通過this訪問組件的常量和狀態變量,并可以在@Styles里通過事件來改變狀態變量的值。
@Component
struct FancyUse {@State heightValue: number = 100@Styles fancy() {.height(this.heightValue) .backgroundColor(Color.Yellow).onClick(() => {this.heightValue = 200 })}
}
- 組件內@Styles的優先級高于全局@Styles。框架優先找當前組件內的@Styles,如果找不到,則會全局查找。
二、以下示例中演示了組件內@Styles和全局@Styles的用法
@Styles function globalFancy () {.width(150).height(100).backgroundColor(Color.Pink)
}@Entry
@Component
struct FancyUse {@State heightValue: number = 100@Styles fancy() {.width(200).height(this.heightValue).backgroundColor(Color.Yellow).onClick(() => {this.heightValue = 200})}build() {Column({ space: 10 }) {Text('FancyA').globalFancy() .fontSize(30)Text('FancyB').fancy() .fontSize(30)}}
}