目录

@Extend装饰器:定义扩展组件样式

在前文的示例中,可以使用@Styles复用样式,在@Styles的基础上,我们提供了@Extend,用于扩展组件样式。

从API version 9开始支持。

从API version 9开始,该装饰器支持在ArkTS卡片中使用。

从API version 11开始,该装饰器支持在元服务中使用。

装饰器使用说明

[h2]语法

@Extend(UIComponentName) function functionName() { ... }

[h2]使用规则

限制条件

使用场景

以下示例声明了3个Text组件,每个Text组件均设置了fontStyle、fontWeight 和backgroundColor样式。

@Entry
@Component
struct FancyUse {
  @State label: string = 'Hello World';

  build() {
    Row({ space: 10 }) {
      // Text组件重复设置样式
      Text(`${this.label}`)
        .fontStyle(FontStyle.Italic)
        .fontWeight(500)
        .backgroundColor(Color.Yellow)
      Text(`${this.label}`)
        .fontStyle(FontStyle.Italic)
        .fontWeight(600)
        .backgroundColor(Color.Pink)
      Text(`${this.label}`)
        .fontStyle(FontStyle.Italic)
        .fontWeight(700)
        .backgroundColor(Color.Orange)
    }.margin('20%')
  }
}

使用@Extend将样式组合复用,示例如下。

// 使用@Extend封装Text样式组合,便于复用
@Extend(Text)
function fancyText(weightValue: number, color: Color) {
  .fontStyle(FontStyle.Italic)
  .fontWeight(weightValue)
  .backgroundColor(color)
}

通过@Extend组合样式后,使得代码更加简洁,增强可读性。

@Entry
@Component
struct FancyUse {
  @State label: string = 'Hello World';

  build() {
    Row({ space: 10 }) {
      // 调用@Extend封装的fancyText复用样式
      Text(`${this.label}`)
        .fancyText(100, Color.Blue)
      Text(`${this.label}`)
        .fancyText(200, Color.Pink)
      Text(`${this.label}`)
        .fancyText(300, Color.Orange)
    }.margin('20%')
  }
}