@Styles裝飾器
定義組件重用樣式
自定義樣式函數使用裝飾器
可以定義在組件內或全局,內部優先級>外部,內部不需要function,外部需要function
定義在組件內的@styles可以通過this訪問組件內部的常量和狀態變量,可以在@styles里通過事件來改變狀態變量
弊端:只支持通用屬性和通用事件 不能傳參
@Entry
@Component
struct StylesFun {@State count: number = 100@State bc: Color|string = Color.Blue// 組件內部@Styles interiorStyle() {.width(200).height(this.count).backgroundColor(this.bc).onClick(() => {this.count++if(this.bc==Color.Blue||this.bc=='blue'){this.bc='green'}else{this.bc='blue'}})}build() {Row() {Column() {Text('我是組件內部@Styles的樣式').fontSize(30).interiorStyle()Text('我是全局@Styles的樣式').fontSize(30).overallStyle()}.width('100%')}.height('100%')}
}
// 全局
@Styles function overallStyle () {.width(150).height(100).backgroundColor(Color.Pink)
}
@Extend裝飾器
定義擴展組件樣式
在@Styles的基礎上,用于擴展原生組件樣式
僅支持定義在全局,不支持在組件內部定義
支持封裝指定的組件的私有屬性和私有事件,也支持預定義相同組件的@Extend的方法
支持參數,可傳遞參數
參數可以為Function,或者 ()=>{} ,作為Event事件,例如:
@Extend(Text) function sizeColor(FSize:string|number,FColor?:string|Color){.fontSize(FSize).fontColor(FColor)
}
@Extend(Button) function testClick(FSize:string|number,click:()=>void) {.fontSize(FSize).width(300).height(50).click()
}
@Entry
@Component
struct ExtendFun {@State message: string = 'Hello World'@State count: number = 0onClickAdd() {this.count++}build() {Row() {Text('我是數字:'+this.count).sizeColor(40,Color.Pink)Button('點我...快點我...').testClick(40,()=>{this.onClickAdd()})}}
}
參數也可以是狀態變量,當狀態變量改變時,UI可以正常的被刷新渲染
當然 這只是我的學習筆記 ,若有什么不足之處還望大佬指出