@ObservedV2 class Person { // 控制Checkbox的选中状态 @Trace public name: boolean; public value: number; constructor(name: boolean, value: number) { this.name = name; this.value = value; } } @ObservedV2 class Info { personList: Person[] = []; constructor() { this.personList = [new Person(false, 0), new Person(false, 1), new Person(false, 2)]; } } @Entry @Component struct CheckboxPage { info: Info = new Info(); build() { Column() { Row() { Text('反选'); } .onClick(() => { // 反转Checkbox的选中状态,实现反选 for (let i = 0; i < this.info.personList.length; i++) { this.info.personList[i].name = !this.info.personList[i].name; } }); List({ space: 0, initialIndex: 0 }) { ForEach(this.info.personList, (item: Person) => { ListItem() { Flex() { Checkbox({ name: item.value.toString() }) .selectedColor('#027cff') .shape(CheckBoxShape.ROUNDED_SQUARE) .unselectedColor('#027cff') .select(item.name) .onChange((value: boolean) => { // 记录当前Checkbox的选中状态 item.name = value; }) .width(18) .height(18); Text(item.value.toString()).fontSize(15).margin({ top: 5 }); }; }; }, (item: Person) => JSON.stringify(item)); }; } .width('100%') .height('100%') .margin({ top: 50 }) .padding({ left: 24, right: 24 }); } }
效果预览:

class CheckName { public id: string; public productName: string; constructor(id: string, productName: string) { this.id = id; this.productName = productName; } } @Entry @Component struct CheckboxExample { @State services: CheckName[] = [ new CheckName('1', 'checkbox1'), new CheckName('2', 'checkbox2'), new CheckName('3', 'checkbox3'), new CheckName('4', 'checkbox4'), ]; @State clickIndex: string = ''; @State clickName: string = ''; @State selectIndexList: Array<string> = []; build() { Scroll() { Column() { // 全选按钮 Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) { CheckboxGroup({ group: 'checkboxGroup' }) .selectedColor('#007DFF') .onChange((itemName: CheckboxGroupResult) => { console.info('checkbox group content' + JSON.stringify(itemName)); }); Text('Select All').fontSize(14).lineHeight(20).fontColor('#182431').fontWeight(500); }.width('auto'); ForEach(this.services, (item: CheckName) => { Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) { Checkbox({ name: item.productName, group: 'checkboxGroup' }) .selectedColor('#007DFF') .onChange((value: boolean) => { this.clickIndex = item.id; this.clickName = item.productName; if (value == true) { this.selectIndexList.push(item.productName); } else { this.selectIndexList = this.selectIndexList.filter((element) => { return element !== item.productName; // 返回不等于要删除元素的元素构成新数组 }); } }); Text(item.productName).fontSize(14).lineHeight(20).fontColor('#182431').fontWeight(500); }.width('auto').margin({ left: 36 }); }, (item: CheckName) => item.id); Text(this.selectIndexList.toString()) .fontSize(14) .lineHeight(20) .fontColor('#182431') .fontWeight(500) .alignSelf(ItemAlign.Center); } .justifyContent(FlexAlign.Center) .width('100%') .height('100%'); }; } }
效果预览:
