
image.png
學(xué)習(xí)了樣式封裝,多態(tài)樣式封裝
概念
設(shè)置組件不同狀態(tài)的樣式。
從API version 9開(kāi)始,該接口支持在ArkTS卡片中使用。
| 名稱 | 狀態(tài) |
|---|---|
| normal | 組件無(wú)狀態(tài)時(shí)的樣式 |
| pressed | 組件按下?tīng)顟B(tài)的樣式 |
| disabled | 組件禁用狀態(tài)的樣式 |
| focused | 組件獲焦?fàn)顟B(tài)的樣式 |
| clicked | 組件點(diǎn)擊狀態(tài)的樣式 |
實(shí)現(xiàn)效果

2024-03-05 14.53.46.gif
代碼
@Entry
@Component
struct StateStylePage {
@State stateButtonEnabled: boolean = true
// 自定義多態(tài)樣式抽離
@Styles stateStyleTextClickedState(){
.height(100)
}
build() {
Row() {
Column({ space: 10 }) {
Text("測(cè)試文本")
.stateStyleTextStyle(44) // 自定義組件樣式
.stateStyles({ // 多態(tài):多種狀態(tài) https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V2/ts-universal-attributes-polymorphic-style-0000001427584836-V2
normal: { // 正常狀態(tài)
.stateStyleTextStyle(44) // 可以直接調(diào)用自定義樣式
},
pressed: { // 按下?tīng)顟B(tài)
.width(300) // 可以直接修改部分屬性
},
// clicked: this.stateStyleTextClickedState // 點(diǎn)擊態(tài) 可以調(diào)用封裝的多態(tài)樣式
})
Button("多態(tài)樣式展示按鈕")
.stateStyleButtonStyle(44)
.enabled(this.stateButtonEnabled)
.stateStyles({
// clicked:{
// .backgroundColor(Color.Green)
// }
normal: {
.stateStyleButtonStyle(44)
},
disabled: { // 禁用狀態(tài)
.backgroundColor(Color.Red)
}
})
Button("切換")
.onClick(() => {
this.stateButtonEnabled = !this.stateButtonEnabled
})
TextInput()
.stateStyles({
normal: {
.border({
color: Color.Gray,
width: 0
})
},
focused: {
.border({
color: Color.Red,
width: 1
})
}
})
TextInput()
.stateStyles({
normal: {
.border({
color: Color.Gray,
width: 0
})
},
focused: {
.border({
color: Color.Red,
width: 1
})
}
})
}.width("100%")
}.height("100%")
}
}
// 自定義組件樣式 可以傳參
@Extend(Text) function stateStyleTextStyle(height: number) {
.fontColor(Color.Red)
.fontSize(20)
.backgroundColor(Color.Pink)
.width(200)
.height(height)
.borderRadius(height / 2)
.textAlign(TextAlign.Center)
}
@Extend(Button) function stateStyleButtonStyle(height: number) {
.fontColor(Color.Black)
.fontSize(20)
.backgroundColor(Color.Gray)
.width(200)
.height(height)
.borderRadius(height / 2)
}
疑問(wèn)
-
clicked狀態(tài)只要是設(shè)置了,默認(rèn)就會(huì)是這個(gè)狀態(tài),為什么?
小結(jié)
- 按鈕不能在設(shè)置樣式的時(shí)候設(shè)置
enabled狀態(tài),需要使用動(dòng)態(tài)屬性設(shè)置 -
TextInput需要同時(shí)設(shè)置normal和focused否則當(dāng)其中一個(gè)失去focused狀態(tài)之后還處于focused樣式