文档管理中心

stateStyles:多态样式

@Styles仅应用于静态页面的样式复用,stateStyles可以依据组件的内部状态的不同,快速设置不同样式。这就是我们本章要介绍的内容stateStyles(又称为:多态样式)。

说明

多态样式仅支持通用属性。如果多态样式不生效,则该属性可能为组件的私有属性,例如:fontColor、TextInput组件的backgroundColor等。此时,可以通过attributeModifier动态设置组件属性来解决此问题。

概述

stateStyles是属性方法,可以根据UI内部状态来设置样式,类似于css伪类,但语法不同。ArkUI提供以下七种状态:

  • focused:获焦态。

  • normal:正常态。

  • pressed:按压态。

  • disabled:不可用态。

  • clicked:点击态。

  • selected10+:选中态。

  • hovered:悬浮态。起始版本: 26.0.0

说明

获焦态目前仅支持通过外接键盘的Tab键或方向键触发,不支持在嵌套滚动组件场景下通过按键触发。

使用场景

基础场景

下面的示例展示了stateStyles最基本的使用场景。Button1处于第一个组件,Button2处于第二个组件。按压时显示为pressed态指定的灰色。使用Tab键走焦,Button1获焦并显示为focused态指定的粉色。当Button2获焦的时候,Button2显示为focused态指定的粉色,Button1失焦显示normal态指定的蓝色。

收起
自动换行
深色代码主题
复制
  1. @Entry
  2. @Component
  3. struct StateStylesSample {
  4. build() {
  5. Column() {
  6. Button('Button1')
  7. .stateStyles({
  8. focused: {
  9. .backgroundColor('#ffffeef0')
  10. },
  11. pressed: {
  12. .backgroundColor('#ff707070')
  13. },
  14. normal: {
  15. .backgroundColor('#ff2787d9')
  16. }
  17. })
  18. .margin(20)
  19. Button('Button2')
  20. .stateStyles({
  21. focused: {
  22. .backgroundColor('#ffffeef0')
  23. },
  24. pressed: {
  25. .backgroundColor('#ff707070')
  26. },
  27. normal: {
  28. .backgroundColor('#ff2787d9')
  29. }
  30. })
  31. }.margin('30%')
  32. }
  33. }

图1 获焦态和按压态

@Styles和stateStyles联合使用

以下示例通过@Styles指定stateStyles的不同状态。

收起
自动换行
深色代码主题
复制
  1. @Entry
  2. @Component
  3. struct MyComponent {
  4. @Styles normalStyle() {
  5. .backgroundColor(Color.Gray)
  6. }
  7. @Styles pressedStyle() {
  8. .backgroundColor(Color.Red)
  9. }
  10. build() {
  11. Column() {
  12. Text('Text1')
  13. .fontSize(50)
  14. .fontColor(Color.White)
  15. .stateStyles({
  16. normal: this.normalStyle,
  17. pressed: this.pressedStyle,
  18. })
  19. }
  20. }
  21. }

图2 正常态和按压态

在stateStyles里使用常规变量和状态变量

stateStyles可以通过this绑定组件内的常规变量和状态变量。

收起
自动换行
深色代码主题
复制
  1. @Entry
  2. @Component
  3. struct CompWithInlineStateStyles {
  4. @State focusedColor: Color = 0xD5D5D5;
  5. normalColor: Color = 0x004AAF;
  6. build() {
  7. Column() {
  8. Button('clickMe')
  9. .height(100)
  10. .width(100)
  11. .stateStyles({
  12. normal: {
  13. .backgroundColor(this.normalColor)
  14. },
  15. focused: {
  16. .backgroundColor(this.focusedColor)
  17. }
  18. })
  19. .onClick(() => {
  20. this.focusedColor = 0x707070;
  21. })
  22. .margin('30%')
  23. }
  24. }
  25. }

Button默认normal态显示蓝色,第一次按下Tab键让Button获焦显示为focus态的浅灰色,点击事件触发后,再次按下Tab键让Button获焦,focus态变为深灰色。

图3 点击改变获焦态样式

在 指南 中进行搜索
请输入您想要搜索的关键词