• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# stateStyles:多态样式
2
3
4\@Styles和\@Extend仅仅应用于静态页面的样式复用,stateStyles可以依据组件的内部状态的不同,快速设置不同样式。这就是我们本章要介绍的内容stateStyles(又称为:多态样式)。
5
6
7## 概述
8
9stateStyles是属性方法,可以根据UI内部状态来设置样式,类似于css伪类,但语法不同。ArkUI提供以下五种状态:
10
11- focused:获焦态。
12
13- normal:正常态。
14
15- pressed:按压态。
16
17- disabled:不可用态。
18
19- selected<sup>10+</sup>:选中态。
20
21
22## 使用场景
23
24
25### 基础场景
26
27下面的示例展示了stateStyles最基本的使用场景。Button1处于第一个组件,Button2处于第二个组件。按压时显示为pressed态指定的黑色。使用Tab键走焦,先是Button1获焦并显示为focus态指定的粉色。当Button2获焦的时候,Button2显示为focus态指定的粉色,Button1失焦显示normal态指定的红色。
28
29
30```ts
31@Entry
32@Component
33struct StateStylesSample {
34  build() {
35    Column() {
36      Button('Button1')
37        .stateStyles({
38          focused: {
39            .backgroundColor(Color.Pink)
40          },
41          pressed: {
42            .backgroundColor(Color.Black)
43          },
44          normal: {
45            .backgroundColor(Color.Red)
46          }
47        })
48        .margin(20)
49      Button('Button2')
50        .stateStyles({
51          focused: {
52            .backgroundColor(Color.Pink)
53          },
54          pressed: {
55            .backgroundColor(Color.Black)
56          },
57          normal: {
58            .backgroundColor(Color.Red)
59          }
60        })
61    }.margin('30%')
62  }
63}
64```
65
66
67  **图1** 获焦态和按压态  
68
69![Video_2023-03-17_120758](figures/Video_2023-03-17_120758.gif)
70
71
72### \@Styles和stateStyles联合使用
73
74以下示例通过\@Styles指定stateStyles的不同状态。
75
76
77
78```ts
79@Entry
80@Component
81struct MyComponent {
82  @Styles normalStyle() {
83    .backgroundColor(Color.Gray)
84  }
85
86  @Styles pressedStyle() {
87    .backgroundColor(Color.Red)
88  }
89
90  build() {
91    Column() {
92      Text('Text1')
93        .fontSize(50)
94        .fontColor(Color.White)
95        .stateStyles({
96          normal: this.normalStyle,
97          pressed: this.pressedStyle,
98        })
99    }
100  }
101}
102```
103
104  **图2** 正常态和按压态  
105
106![Video_2023-03-17_144824](figures/Video_2023-03-17_144824.gif)
107
108
109### 在stateStyles里使用常规变量和状态变量
110
111stateStyles可以通过this绑定组件内的常规变量和状态变量。
112
113
114```ts
115@Entry
116@Component
117struct CompWithInlineStateStyles {
118  @State focusedColor: Color = Color.Red;
119  normalColor: Color = Color.Green
120
121  build() {
122    Column() {
123      Button('clickMe').height(100).width(100)
124        .stateStyles({
125          normal: {
126            .backgroundColor(this.normalColor)
127          },
128          focused: {
129            .backgroundColor(this.focusedColor)
130          }
131        })
132        .onClick(() => {
133          this.focusedColor = Color.Pink
134        })
135        .margin('30%')
136    }
137  }
138}
139```
140
141Button默认normal态显示绿色,第一次按下Tab键让Button获焦显示为focus态的红色,点击事件触发后,再次按下Tab键让Button获焦,focus态变为粉色。
142
143  **图3** 点击改变获焦态样式  
144
145![Video_2023-03-17_144605](figures/Video_2023-03-17_144605.gif)
146