stateStyles 多态样式
@Styles 仅仅应用于静态页面的样式复用,stateStyles 可以依据组件的内部状态的不同,快速设置不同样式。这就是我们本章要介绍的内容 stateStyles(又称为:多态样式)。
INFO
多态仅仅支持通用属性
概述
stateStyles 是属性方法,可以根据 UI 内部状态来设置样式,类似于 css 伪类,但语法不同。ArkUI 提供以下五种状态:
- normal:正常状态,默认状态。
- selected:选中状态。
- disabled:禁用状态。
- focus:聚焦状态。
- pressed:按下状态。
使用场景
基础场景
下面的示例展示了 stateStyles 最基本的使用场景。Button1 处于第一个组件,Button2 处于第二个组件。按压时显示为 pressed 态指定的黑色。使用 Tab 键走焦,先是 Button1 获焦并显示为 focus 态指定的粉色。当 Button2 获焦的时候,Button2 显示为 focus 态指定的粉色,Button1 失焦显示 normal 态指定的蓝色。
bash
@Entry
@Component
struct StateStylesSample {
build() {
Column() {
Button('Button1')
.stateStyles({
focused: {
.backgroundColor('#ffffeef0')
},
pressed: {
.backgroundColor('#ff707070')
},
normal: {
.backgroundColor('#ff2787d9')
}
})
.margin(20)
Button('Button2')
.stateStyles({
focused: {
.backgroundColor('#ffffeef0')
},
pressed: {
.backgroundColor('#ff707070')
},
normal: {
.backgroundColor('#ff2787d9')
}
})
}.margin('30%')
}
}
@Styles 和 stateStyles 联合使用
以下示例通过@Styles 指定 stateStyles 的不同状态
bash
@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 里使用常规变量和状态变量
stateStyles 可以通过 this 绑定组件内的常规变量和状态变量。
bash
@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 默认 normal 态显示绿色,第一次按下 Tab 键让 Button 获焦显示为 focus 态的红色,点击事件触发后,再次按下 Tab 键让 Button 获焦,focus 态变为粉色。