效果展示
代码展示:
interface Item {
title: string
isComplete: boolean
}
@Entry
@Component
struct Index {
@State TaskList: Item[] = [
{ title: '完成作业', isComplete: false },
{ title: '完成复习', isComplete: false },
{ title: '完成预习', isComplete: false },
{ title: '踢足球', isComplete: false },
{ title: '打篮球', isComplete: false },
]
build() {
Column({ space: 10 }) {
Stack() {
Image($r('app.media.1'))
.borderRadius({
topLeft: 20,
topRight: 20
})
.opacity(0.6)
Text('代办任务')
.fontSize(19)
.fontColor(Color.White)
.fontWeight(600)
}
.width('100%')
.height(260)
ForEach(this.TaskList, (item: Item, index: number) => {
Row({ space: 10 }) {
Text(item.title)
.fontSize(18)
.fontColor(Color.White)
.decoration({
type: item.isComplete ? TextDecorationType.LineThrough : TextDecorationType.None
})
Row() {
Button(item.isComplete?'重置':'完成')
.height(35)
.backgroundColor(item.isComplete?Color.Orange:Color.Blue)
.onClick(() => {
this.TaskList[index] = {
title: item.title,
isComplete: !this.TaskList[index].isComplete
}
})
Button('删除')
.onClick(()=>{
this.TaskList.splice(index,1)
})
.backgroundColor(Color.Red)
.height(35)
}
}
.width('100%')
.justifyContent(FlexAlign.SpaceBetween)
})
}
.padding(10)
.width('100%')
.height('100%')
.backgroundColor(Color.Black)
}
}
注意点
问题:修改对象数组中的值:只修改数组值并不会触发状态变量更新视图 解决办法:
1.以对象的形式更改状态变量的值
2.引用数组API的splice(index,1,元素)方式修改