stateStyles:多態(tài)樣式

2024-01-25 12:02 更新

@Styles和@Extend僅僅應(yīng)用于靜態(tài)頁面的樣式復(fù)用,stateStyles可以依據(jù)組件的內(nèi)部狀態(tài)的不同,快速設(shè)置不同樣式。這就是我們本章要介紹的內(nèi)容stateStyles(又稱為:多態(tài)樣式)。

概述

stateStyles是屬性方法,可以根據(jù)UI內(nèi)部狀態(tài)來設(shè)置樣式,類似于css偽類,但語法不同。ArkUI提供以下四種狀態(tài):

  • focused:獲焦態(tài)。
  • normal:正常態(tài)。
  • pressed:按壓態(tài)。
  • disabled:不可用態(tài)。

使用場景

基礎(chǔ)場景

下面的示例展示了stateStyles最基本的使用場景。Button1處于第一個組件,Button2處于第二個組件。按壓時顯示為pressed態(tài)指定的黑色。使用Tab鍵走焦,先是Button1獲焦并顯示為focus態(tài)指定的粉色。當(dāng)Button2獲焦的時候,Button2顯示為focus態(tài)指定的粉色,Button1失焦顯示normal態(tài)指定的紅色。

  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 獲焦態(tài)和按壓態(tài)

@Styles和stateStyles聯(lián)合使用

以下示例通過@Styles指定stateStyles的不同狀態(tài)。

  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 正常態(tài)和按壓態(tài)

在stateStyles里使用常規(guī)變量和狀態(tài)變量

stateStyles可以通過this綁定組件內(nèi)的常規(guī)變量和狀態(tài)變量。

  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默認(rèn)normal態(tài)顯示綠色,第一次按下Tab鍵讓Button獲焦顯示為focus態(tài)的紅色,點(diǎn)擊事件觸發(fā)后,再次按下Tab鍵讓Button獲焦,focus態(tài)變?yōu)榉凵?/p>

圖3 點(diǎn)擊改變獲焦態(tài)樣式

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號