鸿蒙开发状态管理示例
@Observed class Task { static id: number = 1 /*任务序号 静态属性*/ name: string = `任务${Task.id++}` finished: boolean = false } /*统一样式*/ @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 TaskPage { @State totalTask: number = 0 @State finishTask: number = 0 build() { Column({ space: 10 }) { // 1 任务进度卡片 TaskStatistics({ totalTask: this.totalTask, finishTask: this.finishTask }) TaskList({ totalTask: $totalTask, finishTask: $finishTask }) } .width('100%') .height('100%') .backgroundColor('#F1F2F3') } } /*任务统计组件*/ @Component struct TaskStatistics { @Prop totalTask: number @Prop finishTask: number build() { 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) } } /*任务列表组件*/ @Component struct TaskList { @Link totalTask: number @Link finishTask: number @State Tasks: Task[] = [] handleTaskChange() { this.totalTask = this.Tasks.length this.finishTask = this.Tasks.filter(item => item.finished).length } build() { Column() { // 2 新增任务按钮 Button('新增任务').width(200).margin({ bottom: 20 }).onClick(() => { this.Tasks.push(new Task()) this.handleTaskChange() }) // 3 任务列表 List({ space: 10 }) { ForEach(this.Tasks, (item: Task, index: number) => { ListItem() { TaskItem({ item: item, onChangeTask: this.handleTaskChange.bind(this) }) } .swipeAction({ end: this.DeleteButton(index) }) }) } .width('100%') .alignListItem(ListItemAlign.Center) .layoutWeight(1) } } @Builder DeleteButton(index: number) { Button() { Image($r('app.media.delete_big')).width(20).fillColor(Color.White) } .width(40) .height(40) .backgroundColor(Color.Red) .margin(5) .onClick(() => { this.Tasks.splice(index, 1) this.handleTaskChange() }) } } /*任务列表元素*/ @Component struct TaskItem { @ObjectLink item: Task onChangeTask?: () => void build() { Row() { if (this.item.finished) { Text(this.item.name).fontSize(20).finishedTask() } else { Text(this.item.name).fontSize(20) } Checkbox().select(this.item.finished) .onChange(val => { this.item.finished = val if (this.onChangeTask) { this.onChangeTask() } }) } .card() .justifyContent(FlexAlign.SpaceBetween) } }
If the copyright belongs to the longfei, please indicate the source!!!