使用说明
1. @State装饰器标记的变量必须初始化,不能为空值
2. @State支持Object、class、string、number、boolean、enum类型以及这些类型的数组
3. 嵌套类型以及数组中的对象属性无法触发视图更新
使用案例
项目案例
界面预览
代码
class Task{
static id:number = 1
//任务名称
name:string = `任务${Task.id++}`
//任务状态
finished:boolean = false
}
//import {Task} from '../components/Task'
//样式卡片
@Styles function card(){
.width('95%')
.padding(20)
.backgroundColor(Color.White)
.borderRadius(15)
.shadow({radius:6,color:'#1f000000',offsetX:2,offsetY:4})
}
//任务完成样式
@Extend(Text) function finishedTask(){
.decoration({type:TextDecorationType.LineThrough})
.fontColor('#B1B2B1')
}
@Entry
@Component
struct ProPage {
//总任务数量
@State totalTask:number = 0
//已完成任务数量
@State finishTask:number = 0
//任务数组
@State tasks: Task[] = []
handleTaskChange(){
//更新任务数量
this.totalTask = this.tasks.length
//更新已完成任务数量
this.finishTask = this.tasks.filter(item => item.finished).length
//完成的任务变灰色
}
build() {
Column({space:10}){
//任务进度
Row(){
Text('任务进度:').fontSize(30).fontWeight(FontWeight.Bold)
Stack(){//堆叠容器
Progress({//进度样式
value:this.finishTask,
total:this.totalTask,
type:ProgressType.Ring
})
Row(){
Text(this.finishTask.toString()).fontSize(24).fontColor('#36D')
Text(' / '+this.totalTask.toString()).fontSize(24)
}
}
}
.card()
.margin({top:20,bottom:10})
.justifyContent(FlexAlign.SpaceEvenly)
//任务按钮
Button('新增任务')
.width(200)
.onClick(()=>{
//新增任务数据
this.tasks.push(new Task())
this.handleTaskChange()
})
//任务列表
List({space:10}){
ForEach(
this.tasks,
(item:Task,index)=>{
ListItem(){
Row(){
Text(item.name).fontSize(20)
Checkbox()
.select(item.finished)
.onChange( val =>{
//更新当前任务状态
item.finished = val
this.handleTaskChange()
})
}
.card()
.justifyContent(FlexAlign.SpaceBetween)
}
.swipeAction({end:this.DeleteButton(index)})
}
)
}
.width('100%')
.alignListItem(ListItemAlign.Center)
.layoutWeight(1)
}
.width('100%')
.height('100%')
.backgroundColor('#F1F2F3')
}
@Builder DeleteButton(index:number){
Button(){
Image($r('app.media.delete'))
.fillColor(Color.White)
.width(20)
}
.width(40)
.height(40)
.type(ButtonType.Circle)
.backgroundColor(Color.Red)
.margin({left:5})
.onClick(()=>{
this.tasks.splice(index,1)
this.handleTaskChange()
})
}
}
注:个人学习笔记