目录

@Extend Decorator: Defining Extended Component Styles

In the preceding example, @Styles can be used to reuse styles. Building on @Styles, we provide @Extend for extending component styles.

The APIs of this module are supported since API version 9.

This decorator can be used in ArkTS widgets since API version 9.

This decorator can be used in atomic services since API version 11.

How to Use

[h2]Syntax

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

[h2]Usage Rules

Constraints

When to Use

The following example declares three Text components, each configured with fontStyle, fontWeight, and backgroundColor styles.

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

  build() {
    Row({ space: 10 }) {
      // Repeatedly set styles for the Text component.
      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%')
  }
}

Using @Extend for style composition and reuse:

// Use @Extend to encapsulate Text style combinations for easy reuse.
@Extend(Text)
function fancyText(weightValue: number, color: Color) {
  .fontStyle(FontStyle.Italic)
  .fontWeight(weightValue)
  .backgroundColor(color)
}

Simplified code with the use of @Extend:

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

  build() {
    Row({ space: 10 }) {
      // Call the fancyText reusable style encapsulated by @Extend.
      Text(`${this.label}`)
        .fancyText(100, Color.Blue)
      Text(`${this.label}`)
        .fancyText(200, Color.Pink)
      Text(`${this.label}`)
        .fancyText(300, Color.Orange)
    }.margin('20%')
  }
}