鸿蒙开发之组件不同状态样式设置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属性,通过改变定义的属性来改变。

相关推荐
坚果派·白晓明17 小时前
三方库ada
harmonyos·鸿蒙·openharmony
云和数据.ChenGuang1 天前
鸿蒙餐饮系统:全场景智慧餐饮新范式
人工智能·机器学习·华为·数据挖掘·harmonyos·鸿蒙·鸿蒙系统
云和数据.ChenGuang2 天前
鸿蒙智联,极智共生:HarmonyOS与MiniMax智能体的融合新纪元
华为·harmonyos·鸿蒙
UnicornDev2 天前
【HarmonyOS 6】今日统计卡片实战:运动记录数据概览
华为·harmonyos·arkts·鸿蒙·鸿蒙系统
ShuiShenHuoLe2 天前
组件的状态ComponentV2
harmonyos·鸿蒙
仓颉编程语言3 天前
CangjieSkills 正式开源:为仓颉 AI 编程打造的“技能增强“方案,实测降低 60% 费用
华为·ai编程·鸿蒙·仓颉编程语言
左手厨刀右手茼蒿4 天前
Flutter 三方库 all_lint_rules_community 的鸿蒙化适配指南 - 在鸿蒙系统上构建极致、严谨、基于全量社区 Lint 规则的工业级静态代码质量与安全审计引擎
flutter·harmonyos·鸿蒙·openharmony·all_lint_rules_community
雷帝木木4 天前
Flutter for OpenHarmony:Flutter 三方库 cbor 构建 IoT 设备的极致压缩防窃协议(基于标准二进制 JSON 表达格式)
网络·物联网·flutter·http·json·harmonyos·鸿蒙
王码码20354 天前
Flutter 三方库 servicestack 的鸿蒙化适配指南 - 实现企业级 Message-based 架构集成、支持强类型 JSON 序列化与跨端服务调用同步
flutter·harmonyos·鸿蒙·openharmony·message-based
里欧跑得慢4 天前
Flutter 三方库 jsonata_dart 的鸿蒙化适配指南 - 实现高性能的 JSON 数据查询与转换、支持 JSONata 表达式引擎与端侧复杂数据清洗
flutter·harmonyos·鸿蒙·openharmony·jsonata_dart