如何实现列表的上拉加载功能?
主要通过onScrollIndex()方法判断List组件是否滑动到底部,然后通过是否正在加载、是否还有数据两个变量状态判断是否需要加载新的数据。代码如下:
import prompt from '@system.prompt' @Entry@Componentstruct Index { @State private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] @State isLoading:boolean=false; @State hasData:boolean=true; build() { Stack() { List() { ForEach(this.arr, (item) => { ListItem() { Text('' + item) .width('100%') .height(100) .fontSize(16) .textAlign(TextAlign.Center) .borderRadius(10) .backgroundColor(0xFFFFFF) }.editable(true) }, item => item) if(!this.hasData){ ListItem() { Text('没有更多数据了') .width('100%') .height(40) .fontSize(16) .textAlign(TextAlign.Center) .backgroundColor(0xCECECE) } }else { if (this.isLoading && this.hasData) { ListItem() { Text('正在加载数据') .width('100%') .height(40) .fontSize(16) .textAlign(TextAlign.Center) .backgroundColor(0xFFFFFF) } } } } .divider({ strokeWidth: 1, color: 0xcdcdcd}) // 每行之间的分界线 .edgeEffect(EdgeEffect.None) // 滑动到边缘无效果 .onScrollIndex((firstIndex: number, lastIndex: number) => { if(this.hasData&&!this.isLoading&&lastIndex>=this.arr.length-1){ this.isLoading=true; this.loadMoreData(); } console.info('first' + firstIndex+' last' + lastIndex) }) .width('100%') }.width('100%').height('100%').backgroundColor(0xDCDCDC) } loadMoreData(){ prompt.showToast({ message: "加载数据" }); setTimeout(() => { this.isLoading = false this.arr.push(21, 22, 23, 24, 25, 26, 27, 28, 29, 30) this.hasData=false; }, 3000); }}
1
1
1
浏览1032 编辑于2022-01-10 07:25未知归属地
全部评论
最多点赞
最新发布
最早发布
写回答
新增插入模板功能
一键使用模板,快速填写内容,轻松发帖~
知道了
- 为了保障您的信息安全,请勿上传您的敏感个人信息(如您的密码等信息)和您的敏感资产信息(如关键源代码、签名私钥、调试安装包、业务日志等信息),且您需自行承担由此产生的信息泄露等安全风险。
- 如您发布的内容为转载内容,请注明内容来源。
我要发帖子
了解社区公约,与您携手共创和谐专业的开发者社区。






































苏公安网备 32011402010933号