场景一:想要实现在滑动距离到List底部一定高度时就加载更多,此时想要获取ListItem距离底部的高度,是否有什么方式可以实现?
场景二:假如List的高度设置了200vp,但当里面ListItem的高度大于200vp时,就会发生滚动,此时有什么方法或者事件可以获取内部ListItem的总高度呢?
// 模拟分页数据 export class ListDataOne { data: Array<string> = []; totalCount: number = 100; constructor() { for (let index = 0; index < this.totalCount; index++) { this.data.push(index.toString()); } console.info('data', `${this.data}`); } getData(page: number, pageSize: number) { let startIndex = (page - 1) * pageSize; return this.data.slice(startIndex, startIndex + pageSize); } } @Entry @Component struct GetTheHeightOfTheListItemOne { @State arr: Array<string> = []; @State page: number = 1; pageSize = 5; aboutToAppear(): void { let listData = new ListDataOne(); let list = listData.getData(this.page, this.pageSize); list.forEach(item => { this.arr.push(item); }); } build() { RelativeContainer() { List() { ForEach(this.arr, (item: number) => { ListItem() { Text(item.toString()); } .height(200) .width(120) .margin({ bottom: 5 }) .backgroundColor('#ace') .borderRadius(10); }); } .alignListItem(ListItemAlign.Center) .cachedCount(2) .onScrollIndex((start: number, end: number, center: number) => { // 加载最后一个item之前发请求拿新数据 if (end === this.page * this.pageSize - 1) { this.page++; let listData = new ListDataOne(); let list = listData.getData(this.page, this.pageSize); list.forEach(item => { this.arr.push(item); }); console.info('arr', `${this.arr}`); } console.info(`start ${start}`); console.info(`center ${center}`); }); } .height('100%') .width('100%'); } }
效果预览:

@Entry @Component struct GetTheHeightOfTheListItemTwo { @State list: string[] = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']; @State isFlag: boolean = false; build() { Column() { List() { ForEach(this.list, (item: string, index: number) => { ListItem() { Text(item) .width('100%') .fontSize(16) .textAlign(TextAlign.Center) .fontSize(30) .onAreaChange((newValue: Area) => { if (!this.isFlag) { console.info(`${newValue.height}`); // 获取每一个组件的高度 console.info(`length ${this.list.length}`); // 获取总共有多少个组件 console.info(`index ${index} -- ${newValue.height}`); // 获取每个组件 this.isFlag = !this.isFlag; console.info(`sum: ${Number(newValue.height) * this.list.length}`); } }); }; }, (item: string) => item); } .width('100%') .backgroundColor('#DCDCDC') .height(200); } .width('100%') .height('100%'); } }
效果预览:

总共有12个组件,每个组件的高度是35,总和为420。