1.什么是多态样式?
多态样式(stateStyles)在Harmony OS Next开发中,是一种根据组件的内部状态来动态设置样式的强大工具。与传统的静态样式不同,多态样式允许开发者根据组件的不同状态(如按压、获焦、禁用等)定义不同的样式,从而增强用户界面的交互性和美观性。
多态样式的基本概念
多态样式(stateStyles)属于属性方法,它可以根据UI组件的内部状态来设置样式 。这类似于CSS伪类,但语法有所不同 。在鸿蒙系统中,支持的内部状态包括:
focused
:获焦态normal
:正常态pressed
:按压态disabled
:不可用态selected
:选中态
2.如何使用多态样式?
2.1常态和按压态
使用常态和按压态,这里以Text()为主体实现
@Entry
@Component
struct Index {
build() {
Column(){
Text('实现按压态')
.textAlign(TextAlign.Center)
.border({
width:1,
color:'#ccc'
})
.width('100%')
.height(40)
.borderRadius(4)
.backgroundColor('#f5f7f8')
.stateStyles(
{
normal:{
.backgroundColor('#fff') //设置常态下的背景色为白色
},
pressed:{
.backgroundColor(Color.Yellow) //当这行文字被按压时,改变背景颜色
}
}
)
}
.height('100%')
.width('100%')
按压的效果如下:
2.2获焦态
实现focused获焦态如下:
@Entry
@Component
struct focus
{
build(){
Column(){
TextInput()
//设置多态样式
.stateStyles({
//常态效果
normal:{
.border({
width:2,
color:Color.Blue
})
},
//聚焦后的实现效果
focused:{
.border(
{
width:2,
color:Color.Green
}
)
}
})
}
}
}
实现效果:
2.3禁用态
实现禁用态:
@Entry
@Component
struct disable{
build() {
Column(){
TextInput()
Button('提交')
.enabled(false)//禁用按钮
.backgroundColor(Color.Red)
.stateStyles({
disabled:{
.backgroundColor(Color.Blue) //禁用态可以修改遮罩层的样式
}
})
}
}
}
效果:
2.4 选中态
选中态并不常用,读者可自行观看鸿蒙文档学习,这里不做演示。网址如下:stateStyles:多态样式-UI范式基本语法-学习ArkTS语言-基础入门 - 华为HarmonyOS开发者