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