鸿蒙开发之组件不同状态样式设置stateStyles

开发中会有一种场景,组件(如:按钮)在不同状态下展示的样式不同。例如在normal状态和按下状态显示不同的样式,这个时候就可以通过stateStyles属性来设置组件。

TypeScript 复制代码
@Entry
@Component
struct OfficialStateStylePage {
  @State message: string = 'Hello World'
    //设置第二个文本是否可用
  @State textEnable: boolean = true

    //无状态下样式
  @Styles normalStyle() {
    .backgroundColor(Color.Blue)
    .borderWidth(10)
    .borderColor(Color.Green)
    .borderRadius(10)
    .opacity(1)
  }

    //按下的样式
  @Styles pressedStyle() {
    .backgroundColor(Color.Green)
    .borderWidth(20)
    .borderColor(Color.Red)
    .borderRadius(50)
    .opacity(0.5)
  }

    //不可用时的样式
  @Styles unableStyle() {
    .backgroundColor(Color.Gray)
    .borderWidth(5)
    .borderColor(Color.Gray)
    .borderRadius(5)
    .opacity(0.2)
  }

  build() {
    Row() {
      Column({space:30}) {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .onClick(() => {
            //单纯为了让第二个Text可以点击
            this.textEnable = true
          })
          .stateStyles({
            //注意⚠️这里不是this.normalStyle(),是this.normalStyle
            normal: this.normalStyle,
            pressed: this.pressedStyle
          })

        Text(this.textEnable ? '可以点击' : '不可以点击')
          .enabled(this.textEnable)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .onClick(() => {
            //改变组件是否可用
            this.textEnable = !this.textEnable
          })
          .stateStyles({
            normal: this.normalStyle,
            pressed: this.pressedStyle,
            disabled: this.unableStyle
          })
      }
      .width('100%')
    }
    .height('100%')
  }
}

需要说明的是设置的属性都是通用属性。不能设置一些特有属性,例如我想不同状态改变字体大小fontSize,这个做不到。还得需要定义@state属性,通过改变定义的属性来改变。

相关推荐
梁山好汉(Ls_man)28 分钟前
鸿蒙_自定义组件包含多个引用自定义构建函数@BuilderParam时的用法
华为·harmonyos·鸿蒙·arkui
UnicornDev4 小时前
【HarmonyOS 6】鸿蒙原生应用智能体接入
华为·harmonyos·arkts·鸿蒙·鸿蒙系统
梦想不只是梦与想4 小时前
鸿蒙中 PhotoViewPicker:选择图片或视频
harmonyos·鸿蒙·photoviewpicker
星释7 小时前
鸿蒙Flutter实战:29.优先使用联合插件开发鸿蒙化插件
flutter·华为·harmonyos·鸿蒙
加农炮手Jinx12 小时前
Flutter 三方库 better_commit 的鸿蒙化适配指南 - 实现具备语义化提交规范与自动化交互的 Git 工作流插件、支持端侧版本工程的高效规范化审计实战
flutter·harmonyos·鸿蒙·openharmony·better_commit
2301_822703201 天前
渐变壁纸生成:基于鸿蒙Flutter的跨平台壁纸创建工具
flutter·华为·harmonyos·鸿蒙
2301_822703201 天前
开源鸿蒙跨平台Flutter开发:幼儿疫苗全生命周期追踪系统:基于 Flutter 的免疫接种档案与状态机设计
算法·flutter·华为·开源·harmonyos·鸿蒙
2301_822703201 天前
鸿蒙flutter三方库实战——教育与学习平台:Flutter Markdown
学习·算法·flutter·华为·harmonyos·鸿蒙
2301_822703201 天前
开源鸿蒙跨平台Flutter开发:蛋白质序列特征提取:氨基酸组成与理化性质计算
flutter·华为·开源·harmonyos·鸿蒙
钛态1 天前
Flutter 三方库 ethereum_addresses 的鸿蒙化适配指南 - 掌控区块链地址资产、精密校验治理实战、鸿蒙级 Web3 专家
flutter·harmonyos·鸿蒙·openharmony·ethereum_addresses