stateStyles:多态样式

2024-01-25 12:02 更新

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

概述

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

  • focused:获焦态。
  • normal:正常态。
  • pressed:按压态。
  • disabled:不可用态。

使用场景

基础场景

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

  1. @Entry
  2. @Component
  3. struct StateStylesSample {
  4. build() {
  5. Column() {
  6. Button('Button1')
  7. .stateStyles({
  8. focused: {
  9. .backgroundColor(Color.Pink)
  10. },
  11. pressed: {
  12. .backgroundColor(Color.Black)
  13. },
  14. normal: {
  15. .backgroundColor(Color.Red)
  16. }
  17. })
  18. .margin(20)
  19. Button('Button2')
  20. .stateStyles({
  21. focused: {
  22. .backgroundColor(Color.Pink)
  23. },
  24. pressed: {
  25. .backgroundColor(Color.Black)
  26. },
  27. normal: {
  28. .backgroundColor(Color.Red)
  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 = Color.Red;
  5. normalColor: Color = Color.Green
  6. build() {
  7. Column() {
  8. Button('clickMe').height(100).width(100)
  9. .stateStyles({
  10. normal: {
  11. .backgroundColor(this.normalColor)
  12. },
  13. focused: {
  14. .backgroundColor(this.focusedColor)
  15. }
  16. })
  17. .onClick(() => {
  18. this.focusedColor = Color.Pink
  19. })
  20. .margin('30%')
  21. }
  22. }
  23. }

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

图3 点击改变获焦态样式

以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号