美文网首页HarmonyOS学习记录
Harmony学习第三课(stateStyles)

Harmony学习第三课(stateStyles)

作者: Jack陳 | 来源:发表于2024-03-04 15:02 被阅读0次
image.png

学习了样式封装,多态样式封装

概念

设置组件不同状态的样式。
从API version 9开始,该接口支持在ArkTS卡片中使用。

名称 状态
normal 组件无状态时的样式
pressed 组件按下状态的样式
disabled 组件禁用状态的样式
focused 组件获焦状态的样式
clicked 组件点击状态的样式

实现效果

2024-03-05 14.53.46.gif

代码

@Entry
@Component
struct StateStylePage {
  @State stateButtonEnabled: boolean = true
  // 自定义多态样式抽离
  @Styles stateStyleTextClickedState(){
    .height(100)
  }

  build() {
    Row() {
      Column({ space: 10 }) {
        Text("测试文本")
          .stateStyleTextStyle(44) // 自定义组件样式
          .stateStyles({ // 多态:多种状态  https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V2/ts-universal-attributes-polymorphic-style-0000001427584836-V2
            normal: { // 正常状态
              .stateStyleTextStyle(44) // 可以直接调用自定义样式
            },
            pressed: { // 按下状态
              .width(300) // 可以直接修改部分属性
            },
            // clicked: this.stateStyleTextClickedState // 点击态  可以调用封装的多态样式
          })
        Button("多态样式展示按钮")
          .stateStyleButtonStyle(44)
          .enabled(this.stateButtonEnabled)
          .stateStyles({
            // clicked:{
            //   .backgroundColor(Color.Green)
            // }
            normal: {
              .stateStyleButtonStyle(44)
            },
            disabled: { // 禁用状态
              .backgroundColor(Color.Red)
            }
          })
        Button("切换")
          .onClick(() => {
            this.stateButtonEnabled = !this.stateButtonEnabled
          })
        TextInput()
          .stateStyles({
            normal: {
              .border({
                color: Color.Gray,
                width: 0
              })
            },
            focused: {
              .border({
                color: Color.Red,
                width: 1
              })
            }
          })
        TextInput()
          .stateStyles({
            normal: {
              .border({
                color: Color.Gray,
                width: 0
              })
            },
            focused: {
              .border({
                color: Color.Red,
                width: 1
              })
            }
          })
      }.width("100%")
    }.height("100%")
  }
}
// 自定义组件样式 可以传参
@Extend(Text) function stateStyleTextStyle(height: number) {
  .fontColor(Color.Red)
  .fontSize(20)
  .backgroundColor(Color.Pink)
  .width(200)
  .height(height)
  .borderRadius(height / 2)
  .textAlign(TextAlign.Center)
}

@Extend(Button) function stateStyleButtonStyle(height: number) {
  .fontColor(Color.Black)
  .fontSize(20)
  .backgroundColor(Color.Gray)
  .width(200)
  .height(height)
  .borderRadius(height / 2)
}

疑问

  • clicked状态只要是设置了,默认就会是这个状态,为什么?

小结

  • 按钮不能在设置样式的时候设置enabled状态,需要使用动态属性设置
  • TextInput需要同时设置normalfocused否则当其中一个失去focused状态之后还处于focused样式

相关文章

网友评论

    本文标题:Harmony学习第三课(stateStyles)

    本文链接:https://www.haomeiwen.com/subject/ipfrzdtx.html