往期鸿蒙全套实战文章必看:(附带鸿蒙全栈学习资料)
绑定类型的组件和ForEach的正确连用方式
问题现象
bindSheet和foreach合用的问题,$$this.isShow会弹出两次半模态,如果是this.isShow,则半模态弹出的次数是数组的长度数,如何在某一个foreach中的item点击的时候只弹出一个弹窗。
解决措施
给每一个弹窗都绑定一个@State修饰的变量。
参考代码如下:
@Entry
@Component
export struct BindSheetAndForEach {
@State isShow: boolean = false;
@State arr: number[] = [1, 2, 3, 4];
@State isHoverText: Array<boolean> = new Array<boolean>(this.arr.length).fill(false);
@Builder
myBuilder() {
Column() {
Button('content1')
.margin(10)
.fontSize(20)
}
.width('100%')
}
build() {
Column() {
ForEach(this.arr, (item: number, idx: number) => {
Row() {
Text('item')
Button('弹框')
.onClick(() => {
this.isHoverText[idx] = true;
})
.fontSize(15)
.margin(10)
.bindSheet(this.isHoverText[idx], this.myBuilder(), {
backgroundColor: Color.Gray,
height: SheetSize.MEDIUM,
showClose: true,
onDisappear: () => {
this.isHoverText[idx] = false;
}
})
Checkbox()
}
.border({ width: 1, radius: 5 })
})
}
.justifyContent(FlexAlign.Start)
.width('100%')
.height('100%')
}
}