stateStyles:多態(tài)樣式

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

概述

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

  • focused:獲焦態(tài)。
  • normal:正常態(tài)。
  • pressed:按壓態(tài)。
  • disabled:不可用態(tài)。
  • clicked : (當定義這個事件后,normal就不生效了,暫時不知其作用,大神可以幫我補充下)
    其實我是想找,類似于android中的selected狀態(tài),暫時沒看到

基礎場景

@Entry
@Component
struct StateStylesSample {
  build() {
    Column() {
      Button('Button1')
        .stateStyles({
          focused: {
            .backgroundColor(Color.Pink)
          },
          pressed: {
            .backgroundColor(Color.Black)
          },
          normal: {
            .backgroundColor(Color.Red)
          }
        })
        .margin(20)
      Button('Button2')
        .stateStyles({
          focused: {
            .backgroundColor(Color.Pink)
          },
          pressed: {
            .backgroundColor(Color.Black)
          },
          normal: {
            .backgroundColor(Color.Red)
          }
        })
    }.margin('30%')
  }
}

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

@Entry
@Component
struct MyComponent {
  @Styles normalStyle() {
    .backgroundColor(Color.Gray)
  }

  @Styles pressedStyle() {
    .backgroundColor(Color.Red)
  }

  build() {
    Column() {
      Text('Text1')
        .fontSize(50)
        .fontColor(Color.White)
        .stateStyles({
          normal: this.normalStyle,
          pressed: this.pressedStyle,
        })
    }
  }
}

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

@Entry
@Component
struct CompWithInlineStateStyles {
  @State focusedColor: Color = Color.Red;
  normalColor: Color = Color.Green

  build() {
    Column() {
      Button('clickMe').height(100).width(100)
        .stateStyles({
          normal: {
            .backgroundColor(this.normalColor)
          },
          focused: {
            .backgroundColor(this.focusedColor)
          }
        })
        .onClick(() => {
          this.focusedColor = Color.Pink
        })
        .margin('30%')
    }
  }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容