鸿蒙ArkTS-List列表下拉刷新案例
1. 效果图
鸿蒙ArkTS中List和ForEach语法配合实现列表下拉刷新效果
页面使用List
展示一个集合的数据,然后高度超过屏幕后出现上下滑动效果,往下拉动列表时,可以触发函数加载新的数据
2. 代码
页面代码如下:(拷贝粘贴可直接看效果)
class ImageModel {img: stringtitle: stringconstructor(img: string, title: string) {this.img = img;this.title = title;}
}/*** Author: 波波老师(weixin:javabobo0513)* Desc: List下拉刷新页面案例*/
@Entry
@Component
struct ListPageTest {@State dataList: Array<ImageModel> = [new ImageModel('https://img1.baidu.com/it/u=3320367047,2243749821&fm=253&fmt=auto&app=138&f=JPEG?w=300&h=300','帅哥1号'),new ImageModel('https://img2.baidu.com/it/u=1869953151,201394433&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500','美女1号'),new ImageModel('https://img0.baidu.com/it/u=630464712,2423649495&fm=253&fmt=auto&app=120&f=JPEG?w=800&h=800','美女2号'),new ImageModel('https://img0.baidu.com/it/u=804560255,390146878&fm=253&fmt=auto&app=138&f=JPEG?w=380&h=380','美女头像谁不爱呢'),new ImageModel('https://img1.baidu.com/it/u=3320367047,2243749821&fm=253&fmt=auto&app=138&f=JPEG?w=300&h=300','帅哥1号'),new ImageModel('https://img2.baidu.com/it/u=1869953151,201394433&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500','美女1号'),new ImageModel('https://img0.baidu.com/it/u=630464712,2423649495&fm=253&fmt=auto&app=120&f=JPEG?w=800&h=800','美女2号'),new ImageModel('https://img0.baidu.com/it/u=804560255,390146878&fm=253&fmt=auto&app=138&f=JPEG?w=380&h=380','美女头像谁不爱呢'),new ImageModel('https://img1.baidu.com/it/u=3320367047,2243749821&fm=253&fmt=auto&app=138&f=JPEG?w=300&h=300','帅哥1号'),new ImageModel('https://img2.baidu.com/it/u=1869953151,201394433&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500','美女1号'),new ImageModel('https://img0.baidu.com/it/u=630464712,2423649495&fm=253&fmt=auto&app=120&f=JPEG?w=800&h=800','美女2号'),new ImageModel('https://img0.baidu.com/it/u=804560255,390146878&fm=253&fmt=auto&app=138&f=JPEG?w=380&h=380','美女头像谁不爱呢'),];@State isRefreshing: boolean = false; //刷新标识aboutToAppear() {this.loadData(); //进入页面就调用 loadData 方法}//加载数据loadData() {//5秒后再关闭刷新效果,模拟调用后台接口耗时setInterval(() => {//真实场景中,调用后台接口后,执行下面代码关闭下拉效果即可this.isRefreshing = false; //关闭下拉加载效果}, 5000)}build() {Column() {//Refresh:可以进行页面下拉操作并显示刷新动效的容器组件//refreshing:组件当前是否处于刷新中状态Refresh({ refreshing: $$this.isRefreshing, promptText: '数据加载中...' }) {List({ space: 8 }) {ForEach(this.dataList, (item: ImageModel) => {ListItem() {Column({ space: 5 }) {Image(item.img).width('100%').height(160).borderRadius(5)Text(item.title).fontSize(18).fontWeight(500).fontColor('#111111')}.borderRadius(5).padding(5).shadow({radius: 20,color: '#ffa7a6a6',offsetX: 5,offsetY: 5}) //阴影效果.width('97%')}})}.width('100%').height('100%').scrollBar(BarState.Off) //关闭滚动条.alignListItem(ListItemAlign.Center) //居中显示.lanes(2) //每行显示2列}//进入刷新状态时触发回调.onRefreshing(() => {//下拉时调用接口获取最新数据this.loadData();}).refreshOffset(90) //设置触发刷新的下拉偏移量.pullToRefresh(true) //设置当下拉距离超过refreshOffset时是否能触发刷新}.width('100%').height('100%')}
}