开源鸿蒙 @Styles

  • 2022-08-09
  • 浏览 (773)

@Styles

@Styles装饰器将新的属性函数添加到基本组件上,如Text、Column、Button等。当前@Styles仅支持通用属性。通过@Styles装饰器可以快速定义并复用组件的自定义样式。

@Styles可以定义在组件内或组件外,在组件外定义时需在方法前添加function关键字,组件内定义时不需要添加function关键字。

// xxx.ets
@Styles function globalFancy() {
  .backgroundColor(Color.Red)
}

@Entry
@Component
struct FancyUse {
  @Styles componentFancy() {
    .backgroundColor(Color.Blue)
  }
  build() {
    Column({ space: 10 }) {
      Text("Fancy")
        .globalFancy()
        .width(100)
        .height(100)
        .fontSize(30)
      Text("Fancy")
        .componentFancy()
        .width(100)
        .height(100)
        .fontSize(30)
    }
  }
}

@Styles还可以在StateStyles属性内部使用,在组件处于不同的状态时赋予相应的属性。

在StateStyles内可以直接调用组件外定义的Styles,但需要通过this关键字调用组件内定义的Styles。

// xxx.ets
@Styles function globalFancy() {
  .width(100)
  .height(100)
}

@Entry
@Component
struct FancyUse {
  @Styles componentFancy() {
    .width(50)
    .height(50)
  }
  build() {
    Row({ space: 10 }) {
      Button() {
      	Text("Fancy")
      }
      .stateStyles({
      	normal: {
      	  .width(80)
      	  .height(80)
      	},
      	disabled: this.componentFancy,
      	pressed: globalFancy
      })
    }
  }
}

你可能感兴趣的文章

开源鸿蒙 UI开发

开源鸿蒙 方舟开发框架概述

开源鸿蒙 文件组织

开源鸿蒙 app.js

开源鸿蒙 js标签配置

开源鸿蒙 生命周期

开源鸿蒙 多语言支持

开源鸿蒙 资源限定与访问

开源鸿蒙 CSS语法参考

开源鸿蒙 HML语法参考

0  赞