@Styles可以定義在組件內或全局,在全局定義時需在方法名前面添加function關鍵字,組件內定義時則不需要添加function關鍵字。
組件內@Styles的優先級高于全局@Styles。
框架優先找當前組件內的@Styles,如果找不到,則會全局查找。
// 全局
@Styles function functionName() { ... }// 在組件內
@Component
struct FancyUse {@Styles fancy() {.height(100)}
}
// 定義在全局的@Styles封裝的樣式
@Styles function globalFancy () {.width(150).height(100).backgroundColor(Color.Pink)
}@Entry
@Component
struct FancyUse {@State heightValue: number = 100// 定義在組件內的@Styles封裝的樣式@Styles fancy() {.width(200).height(this.heightValue).backgroundColor(Color.Yellow).onClick(() => {this.heightValue = 200})}build() {Column({ space: 10 }) {// 使用全局的@Styles封裝的樣式Text('FancyA').globalFancy ().fontSize(30)// 使用組件內的@Styles封裝的樣式Text('FancyB').fancy().fontSize(30)}}
}