List组件按需加载的特性使得每次只有当前可见项被渲染,导致全选时无法选中所有组件,可以在List组件外再套一层Scroll组件,确保所有组件可以被渲染。
@Entry @Component struct SelectAllCheckBoxSample { @State dataArray: string[] = []; aboutToAppear(): void { for (let i = 0; i < 50; i++) { this.dataArray.push(i + ''); } } build() { Row() { Column() { Flex({ justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) { CheckboxGroup({ group: 'checkboxGroup' }) .checkboxShape(CheckBoxShape.ROUNDED_SQUARE) .selectedColor('FF0858F8') .onChange((itemName: CheckboxGroupResult) => { console.info(`checkbox group content ${JSON.stringify(itemName)} `); }) .mark({ strokeColor: Color.White, size: 40, strokeWidth: 5 }) .unselectedColor(Color.Gray) .width(30) .height(30) Text('Select All').fontSize(20); }.margin({ right: 40 }) Scroll() { // 在外面套一层scroll List() { ForEach(this.dataArray, (item: string, index: number) => { ListItem() { Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) { Checkbox({ name: 'checkbox' + index, group: 'checkboxGroup' }) .selectedColor('FF0858F8') .shape(CheckBoxShape.ROUNDED_SQUARE) .onChange((value: boolean) => { console.info(`Checkbox${index}change is${value}`); }) .mark({ strokeColor: Color.White, size: 50, strokeWidth: 5 }) .unselectedColor(Color.Gray) .width(30) .height(30) Text(`Checkbox${index}`).fontSize(20); } .width(160) }.backgroundColor(Color.White) } ) } .alignListItem(ListItemAlign.Center) .width('100%') } }.layoutWeight(1) .width(300) .height('100%') } .height('100%') .margin({ top: '16PX' }) } }