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

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

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

js 复制代码
/**
 * @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 扩展组件样式

js 复制代码
/**
 *@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()
  })
}

多态样式

js 复制代码
/**
 * 多态样式
 */
@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%')
  }
}
相关推荐
nashane35 分钟前
HarmonyOS 6学习:PanGesture手势驱动月亮半圆轨迹“滚动”术
学习·harmonyos 5
叶~小兮1 小时前
K8S进阶核心综合学习笔记(持久化存储+特殊容器+调度管理)
笔记·学习·kubernetes
li星野1 小时前
位运算 & 数学 & 高频进阶九题通关(Python + C++)
c++·python·学习·算法
y = xⁿ3 小时前
Java并发八股学习日记
java·开发语言·学习
@codercjw4 小时前
工程图制图经验
学习
星幻元宇VR4 小时前
VR文旅大空间|沉浸式体验重塑文旅新场景
科技·学习·安全·vr·虚拟现实
Cat_Rocky4 小时前
K8S-Helm简单学习分享
学习·容器·kubernetes
NNYSJYKJ4 小时前
告别刷题无效与偏科:脑能模型解锁 K12 学习底层能力构建
学习
凌云若寒5 小时前
BarTender许可 | 关于PDF打印数量说明
学习·pdf·产品经理·制造·软件需求
一只机电自动化菜鸟5 小时前
一建机电备考笔记(36) 焊接技术—焊接方法与工艺(含考频+题型)
笔记·学习·职场和发展·生活·学习方法