04-鸿蒙4.0学习之样式装饰器
@styles装饰器:定义组件重用样式
@Entry
@Component
struct StyleUI {@State message: string = '@styles'@Styles commonStyle(){.width(200).height(100).backgroundColor(Color.Gray).margin(5)}build() {Row() {Column() {Text(this.message).fontSize(50).fontWeight(FontWeight.Bold).commonStyle()Button().commonStyle()Image('').commonStyle()Row(){}.commonStyle()}.width('100%')}.height('100%')}
}
@Extend 扩展组件样式
@Entry
@Component
struct ExtendFun {@State message: string = '@Extend'@State count: number = 0build() {Row() {Column() {Text(this.message).fontSize(50).fontWeight(FontWeight.Bold)Divider()Text('HarmonyOS4.0').sizeColor(40, Color.Blue)Text('第二行').sizeColor(40, 'red')Text('第三行').textStyle(20, "#6699ff")Text('第四行').textStyle(50, Color.Pink)Button(this.count.toString()).btnStyle(()=>{this.count++})}.width('100%')}.height('100%')}
}@Extend(Text) function sizeColor(fs: number, fc: Color | string) {.fontSize(fs).fontColor(fc)
}@Extend(Text) function textStyle(fs: number, fc: Color | string) {.sizeColor(fs, fc).fontStyle(FontStyle.Italic).fontWeight(FontWeight.Bold)
}@Extend(Button) function btnStyle(click:()=>void) {.fontSize(40).width(150).height(50).onClick(()=>{click()})
}
多态样式
@Entry
@Component
struct StateStyleFun {@State message: string = 'stateStyles()'build() {Row() {Column() {Button(this.message).fontSize(50).fontWeight(FontWeight.Bold).stateStyles({normal: {.backgroundColor(Color.Red)},focused: {.backgroundColor(Color.Pink)},pressed: {.backgroundColor(Color.Blue)}})}.width('100%')}.height('100%')}
}