W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
@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):
下面的示例展示了stateStyles最基本的使用場(chǎng)景。Button1處于第一個(gè)組件,Button2處于第二個(gè)組件。按壓時(shí)顯示為pressed態(tài)指定的黑色。使用Tab鍵走焦,先是Button1獲焦并顯示為focus態(tài)指定的粉色。當(dāng)Button2獲焦的時(shí)候,Button2顯示為focus態(tài)指定的粉色,Button1失焦顯示normal態(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%')
- }
- }
- @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可以通過this綁定組件內(nèi)的常規(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%')
- }
- }
- }
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)樣式
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: