1# stateStyles: Polymorphic Style 2 3 4Unlike \@Styles and \@Extend, which are used to reuse styles only on static pages, stateStyles enables you to set state-specific styles. 5 6 7## Overview 8 9stateStyles is an attribute method that sets the style based on the internal state of a component. It is similar to a CSS pseudo-class, with different syntax. ArkUI provides the following states: 10 11- focused 12 13- normal 14 15- pressed 16 17- disabled 18 19 20## Application Scenarios 21 22 23### Common Scenarios 24 25This example shows the most basic application scenario of stateStyles. The **\<Button>** component is the first component and is in the default focused state, where the pink style specified for **focused** takes effect. When the component is pressed, the black style specified for **pressed** takes effect. If you place another component before the **\<Button>** component and have it in the normal state, the yellow style specified for **normal** takes effect. 26 27 28```ts 29@Entry 30@Component 31struct StateStylesSample { 32 build() { 33 Column() { 34 Button('Click me') 35 .stateStyles({ 36 focused: { 37 .backgroundColor(Color.Pink) 38 }, 39 pressed: { 40 .backgroundColor(Color.Black) 41 }, 42 normal: { 43 .backgroundColor(Color.Yellow) 44 } 45 }) 46 }.margin('30%') 47 } 48} 49``` 50 51 52 **Figure 1** Focused and pressed states 53 54![Video_2023-03-17_120758](figures/Video_2023-03-17_120758.gif) 55 56 57### Combined Use of \@Styles and stateStyles 58 59The following example uses \@Styles to specify different states of stateStyles. 60 61 62 63```ts 64@Entry 65@Component 66struct MyComponent { 67 @Styles normalStyle() { 68 .backgroundColor(Color.Gray) 69 } 70 71 @Styles pressedStyle() { 72 .backgroundColor(Color.Red) 73 } 74 75 build() { 76 Column() { 77 Text('Text1') 78 .fontSize(50) 79 .fontColor(Color.White) 80 .stateStyles({ 81 normal: this.normalStyle, 82 pressed: this.pressedStyle, 83 }) 84 } 85 } 86} 87``` 88 89 **Figure 2** Normal and pressed states 90 91![Video_2023-03-17_144824](figures/Video_2023-03-17_144824.gif) 92 93 94### Using Regular Variables and State Variables in stateStyles 95 96stateStyles can use **this** to bind regular variables and state variables in a component. 97 98 99```ts 100@Entry 101@Component 102struct CompWithInlineStateStyles { 103 @State focusedColor: Color = Color.Red; 104 normalColor: Color = Color.Green 105 106 build() { 107 Button('clickMe').height(100).width(100) 108 .stateStyles({ 109 normal: { 110 .backgroundColor(this.normalColor) 111 }, 112 focused: { 113 .backgroundColor(this.focusedColor) 114 } 115 }) 116 .onClick(() => { 117 this.focusedColor = Color.Pink 118 }) 119 .margin('30%') 120 } 121} 122``` 123 124By default, the **\<Button>** component is in red when focused. After a click event is triggered, it turns to pink when focused. 125 126 **Figure 3** Change of the styles in focused state by a click 127 128![Video_2023-03-17_144605](figures/Video_2023-03-17_144605.gif) 129