【鸿蒙ArkTS】用组件List显示数据上拉分页
在鸿蒙 ArkTS 中,使用List渲染数据下拉分页。
·
在鸿蒙 ArkTS 中,使用 List 组件结合分页机制实现上拉加载功能需要以下步骤:
- 准备数据源:定义一个存储分页数据的数组。
- 实现分页逻辑:在滚动到底部时,加载更多数据。
- 动态更新列表:随着数据加载完成,更新
List的内容。
以下是完整的实现代码示例:
示例代码
import { ObservedPropertySimple } from '@ohos/state';
import { List, LazyForEach, Text, FlexAlign, Button, Divider } from '@ohos/base';
// 模拟网络请求获取分页数据
function fetchPageData(page: number, pageSize: number): Promise<Array<any>> {
return new Promise((resolve) => {
setTimeout(() => {
const data = Array.from(
{ length: pageSize },
(_, index) => ({
id: page * pageSize + index + 1,
title: `商品标题 ${page * pageSize + index + 1}`,
price: (Math.random() * 100).toFixed(2),
})
);
resolve(data);
}, 1000); // 模拟网络延迟
});
}
// App Component
@Entry
@Component
export struct App {
private currentPage: number = 0; // 当前页码
private pageSize: number = 10; // 每页条数
private isLoading: ObservedPropertySimple<boolean> = new ObservedPropertySimple(false);
private hasMore: ObservedPropertySimple<boolean> = new ObservedPropertySimple(true);
private items: ObservedPropertySimple<Array<any>> = new ObservedPropertySimple([]);
// 初始化数据
aboutToAppear() {
this.loadMore();
}
// 加载更多数据
private async loadMore() {
if (this.isLoading.get() || !this.hasMore.get()) {
return;
}
this.isLoading.set(true);
const newData = await fetchPageData(this.currentPage, this.pageSize);
this.items.set([...this.items.get(), ...newData]);
this.currentPage++;
// 如果返回的数据不足一页,说明没有更多数据了
if (newData.length < this.pageSize) {
this.hasMore.set(false);
}
this.isLoading.set(false);
}
build() {
return Column {
// 标题栏
Text('商品列表')
.fontSize(20)
.width('100%')
.textAlign(TextAlign.Center)
.padding({ top: 10, bottom: 10 })
// 商品列表
List {
LazyForEach(this.items.get(), (item) => {
return Column {
Text(`商品名称: ${item.title}`).fontSize(16).margin(10)
Text(`价格: ¥${item.price}`).fontSize(14).margin({ left: 10, bottom: 10 })
Divider().width('100%').color('#CCCCCC').height(1)
};
})
// 上拉加载更多触发器
if (this.hasMore.get()) {
Button('加载更多')
.onClick(() => this.loadMore())
.width('100%')
.padding(10)
.alignSelf(FlexAlign.Center);
} else {
Text('没有更多数据了')
.fontSize(14)
.textAlign(TextAlign.Center)
.margin(10);
}
}
.width('100%')
.height('80%')
.onScroll((offset) => {
// 检测是否到底部,触发分页加载
if (offset >= 0.9) {
this.loadMore();
}
})
};
}
}
代码解析
-
分页逻辑:
fetchPageData:模拟网络请求,返回分页数据。loadMore:检查当前是否正在加载数据或是否还有更多数据,避免重复加载。
-
组件绑定:
LazyForEach:动态渲染List的子项。List.onScroll:监听列表滚动事件,当滚动接近底部时自动加载更多数据。
-
状态管理:
- 使用
ObservedPropertySimple存储和监听items、isLoading和hasMore,实现响应式更新。
- 使用
-
用户体验:
- 显示“加载更多”按钮,允许用户手动加载。
- 数据加载完成后,如果没有更多数据,则提示“没有更多数据”。
更多推荐



所有评论(0)