HarmonyOS NEXT学习——@Styles、@Extend、stateStyles

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

  • 仅支持通用属性通用事件
  • 不支持参数
  • 可以定义全局和组件内使用,全局使用需要加function
javascript 复制代码
// 全局
@Styles function functionName() { ... }

// 在组件内
@Component
struct FancyUse {
  @Styles fancy() {
    .height(100)
  }
}
  • 组件内@Styles的优先级高于全局@Styles。
javascript 复制代码
// 定义在全局的@Styles封装的样式
@Styles function globalFancy  () {
  .width(100)
  .height(100)
  .backgroundColor(Color.Pink)
}

@Entry
@Component
@Preview
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)
      //组件内优先级高于全局
      Text('FancyAB')
        .globalFancy()
        .fancy()
        .fontSize(30)
    }
    .alignItems(HorizontalAlign.Start)
  }
}

@Extend装饰器:定义扩展组件样式

  • @Styles用于样式的扩展
  • 可以传参数
  • 仅能全局定义
javascript 复制代码
@Extend(Text) function fancyText(weightValue: number, color: Color,clickE:()=>void) {
  .fontStyle(FontStyle.Italic)
  .fontSize(weightValue)
  .backgroundColor(color)
  .onClick(clickE)
}
@Entry
@Component
struct FancyUse {
  @State label: string = 'Hello World'

  onClickHandler(){
    console.log('40')
  }
  build() {
    Column() {
      Text(`${this.label}`)
        .fancyText(30, Color.Blue,()=>{console.log('30')})
      Text(`${this.label}`)
        .fancyText(40, Color.Pink,()=>{this.onClickHandler()})
      Text(`${this.label}`)
        .fancyText(50, Color.Orange,()=>{console.log('50')})
    }
    .alignItems(HorizontalAlign.Start)
  }
}

三个点击事件

stateStyles 多态样式

stateStyles是属性方法,可以根据UI内部状态来设置样式,类似于css伪类,但语法不同。ArkUI提供以下五种状态:

  • focused:获焦态。
  • normal:正常态。
  • pressed:按压态。
  • disabled:不可用态。
  • selected:选中态。
javascript 复制代码
@Entry
@Component
struct FancyUse {
  @State label: string = 'Hello World'

  build() {
    Column() {
      Text(`${this.label}`)
        .stateStyles({
          normal:{
            .backgroundColor(Color.Yellow)
          },
          pressed:{
            .backgroundColor(Color.Pink)
          }
        })
        .fontSize(40)
    }
    .alignItems(HorizontalAlign.Start)
  }
}
相关推荐
许白掰21 分钟前
Linux入门篇学习——Linux 编写第一个自己的命令
linux·运维·数据库·嵌入式硬件·学习
生如夏花℡36 分钟前
HarmonyOS学习记录4
学习·华为·harmonyos
彤银浦44 分钟前
Web学习笔记2
笔记·学习
xq95271 小时前
编程之路2025年中总结,勇往直前 再战江湖
harmonyos
长风破浪会有时呀1 小时前
Git 学习笔记
笔记·git·学习
偷偷的卷1 小时前
【算法笔记 day three】滑动窗口(其他类型)
数据结构·笔记·python·学习·算法·leetcode
大白的编程日记.1 小时前
【计算机基础理论知识】C++篇(二)
开发语言·c++·学习
Chef_Chen1 小时前
从0开始学习R语言--Day42--LM检验
学习
C语言小火车1 小时前
野指针:C/C++内存管理的“幽灵陷阱”与系统化规避策略
c语言·c++·学习·指针
Chef_Chen2 小时前
从0开始学习R语言--Day40--Kruskal-Wallis检验
开发语言·学习·r语言