鸿蒙 ArkUI-Style封装

在我们日常开发当中是否会经常遇到重复样式,如下图


image.png

我们可以将样式封装成公共样式,用@Styles关键词,代码如下

一、定义公共样式

将代码放于文件的最上面

/**
 * 全局公共样式函数
 */
@Styles function fillScreen(){
  .width('100%')
  .height('100%')
  .backgroundColor('#efefef')
  .padding(20)
}

/**
 * 全局集成扩展样式(只能给Text使用)
 */
@Extend(Text) function priceText(fontColor: ResourceColor = '#F36', fontSize: string|number|Resource = 18){
  .fontColor(fontColor)
  .fontSize(fontSize)
}

这个时候有人要问了,@Style和@Extend有什么区别
@Style只能封装公共样式,就是所有ArkUI组件都具备的样式属性,比如width,height等等
@Extend 只能扩展制定ArkUI组件的样式,比如@Extend(Text) 就只能写Text特有的样式,@Extend(Image)就只能写Image特有的样式。

二、使用公共样式

//使用fillScreen代码一
build() {
    Row() {
      Column({ space: 8 }) {
          //代码略
      }
      .fillScreen()
    }
  }

//使用priceText代码二
Column({ space: 4 }) {

        if (item.discount) {
          Text(item.name)
          Text('原价:¥' + item.price)
            .decoration({ type: TextDecorationType.LineThrough })
            .priceText('#ccc')
          Text('折扣价:¥' + (item.price - item.discount))
            .priceText()
          Text('补贴:¥' + item.discount)
            .priceText()
        } else {
          Text(item.name)
          Text('¥' + item.price)
            .priceText()
        }

      }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容