ts-component-based-styles.md 1.6 KB
Newer Older
G
ge-yafang 已提交
1 2 3
# @Styles


E
ester.zhou 已提交
4
The **@Styles** decorator adds new attribute functions to basic components, such as **\<Text>**, **\<Column>**, and **\<Button>**. Currently, **@Styles** supports only universal attributes. You can use the **@Styles** decorator to quickly define and reuse the custom styles of a component.
G
ge-yafang 已提交
5

E
ester.zhou 已提交
6
**@Styles** can be defined inside or outside a component. When it is defined outside a component, the keyword **function** must be added before the API name.
G
ge-yafang 已提交
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37



```
@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)
    }
  }
}
```

E
ester.zhou 已提交
38
**@Styles** can also be used inside the **StateStyles** attribute to assign state-specific attributes to components.
G
ge-yafang 已提交
39 40


E
ester.zhou 已提交
41
In **StateStyles**, styles defined outside the component can be directly called. However, the keyword **this** must be used to call styles defined in the component.
G
ge-yafang 已提交
42 43 44 45 46 47 48 49 50 51

```
@Styles function globalFancy() {
  .width(100)
  .height(100)
}

@Entry
@Component
struct FancyUse {
E
ester.zhou 已提交
52
  @Styles componentFancy() {
G
ge-yafang 已提交
53 54 55 56 57 58
    .width(50)
    .height(50)
  }
  build() {
    Row({ space: 10 }) {
      Button() {
E
ester.zhou 已提交
59
      	Text("Fancy")
G
ge-yafang 已提交
60 61
      }
      .stateStyles({
E
ester.zhou 已提交
62 63 64 65 66 67
      	normal: {
      	  .width(80)
      	  .height(80)
      	},
      	disabled: this.componentFancy,
      	pressed: globalFancy
G
ge-yafang 已提交
68 69 70 71 72
      })
    }
  }
}
```