04-鸿蒙4.0学习之样式装饰器相关

本文详细介绍了鸿蒙4.0中样式装饰器的使用,如@styles用于定义组件通用样式,@Extend用于扩展组件样式并支持传参和动态修改。还讨论了多态样式在不同状态下的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

04-鸿蒙4.0学习之样式装饰器

@styles装饰器:定义组件重用样式

/**
 * @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%')
  }
}
// 外部通用样式函数 使用function 关键字 内部样式函数 内部不需要function  内部优先级 > 外部样式
// 弊端:只能写通用样式 不能传参
//  @Styles function commonStyle(){
//    .width(200)
//    .height(100)
//    .backgroundColor(Color.Gray)
//   }

@Extend 扩展组件样式

/**
 *@Extend 扩展组件样式
 */
@Entry
@Component
struct ExtendFun {
  @State message: string = '@Extend'
  @State count: number = 0

  build() {
    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%')
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值