@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%')
}
}
}