鸿蒙:简单实现列表下拉刷新+上拉加载
《目录》
1. 前言
2. 参考文档
3. 核心代码
4. 运行效果
5. 完整代码
1. 前言
下拉刷新和上拉加载,是List()组件中比较常用功能。鸿蒙开发中,实现这一功能是比较简单的,结合Refresh、onReachEnd等组件或方法即可实现。
2. 参考文档
https://developer.huawei.com/consumer/cn/doc/harmonyos-references/ts-container-list#onreachend
https://developer.huawei.com/consumer/cn/doc/harmonyos-references/ts-container-refresh
3. 核心代码
Refresh({ refreshing: $$this.isRefreshing }) {List({ space: 20 }) {ForEach(this.arr.arr, (item: string) => {ListItem() {Text(item).width('90%').height(80).fontSize(16).margin(10).textAlign(TextAlign.Center).borderRadius(10).backgroundColor(0xFFFFFF).padding({ left: 10, right: 10 }).maxLines(2).textOverflow({ overflow: TextOverflow.Ellipsis })}.shadow({ radius: 40, color: "rgba(0, 0, 0, 0.5)" }).borderRadius(10)}, (item: string) => item)}.onScrollIndex((first: number) => {console.info(first.toString());}).onReachEnd(() => {if (!this.isEnd) {this.isEnd = truefor (let index = 0; index < 5; index++) {this.num++this.arr.arr.push("Hello" + this.num)}this.isEnd = false}}).width('100%').height("95%").alignListItem(ListItemAlign.Center).scrollBar(BarState.Off)
}.onRefreshing(() => {setTimeout(() => {const arr = new Arr().arrthis.arr.arr = arrthis.isRefreshing = false;this.getUIContext().getPromptAction().showToast({ message: "刷新成功" })}, 2000)
4. 运行效果


5. 完整代码
@ObservedV2
class Arr {@Tracearr: String[] = ["我对钱没有兴趣,真的,我从来没碰过钱💰","我最快乐的时候,是一个月拿91块钱当老师的时候😌","年轻人,晚上想想千条路,早上起来走原路🤷♂️","创业要找最适合的人,不要找最好的人👥","当你成功的时候,你说的所有话都是真理💬","如果我能成功,80%的人都能成功💪","我高考数学考了1分,这说明我不适合学数学📚","我从来没当过首富,我只是个普通人🙋♂️","今天很残酷,明天更残酷,后天很美好,但绝对大部分人死在明天晚上🌙","男人的长相往往和他的才华成反比😜","我退休不是因为我赚够了钱,而是因为我想做更多喜欢的事🎉"];
}@Entry
@ComponentV2
struct Index {@Local isRefreshing: boolean = false;arr = new Arr()@Local num: number = 0;@Local isEnd: boolean = false;build() {Column() {Text("下拉刷新 + 上拉加载").fontSize(30).fontWeight(FontWeight.Bold).width('100%').textAlign(TextAlign.Center)Refresh({ refreshing: $$this.isRefreshing }) {List({ space: 20 }) {ForEach(this.arr.arr, (item: string) => {ListItem() {Text(item).width('90%').height(80).fontSize(16).margin(10).textAlign(TextAlign.Center).borderRadius(10).backgroundColor(0xFFFFFF).padding({ left: 10, right: 10 }).maxLines(2).textOverflow({ overflow: TextOverflow.Ellipsis })}.shadow({ radius: 40, color: "rgba(0, 0, 0, 0.5)" }).borderRadius(10)}, (item: string) => item)}.onScrollIndex((first: number) => {console.info(first.toString());}).onReachEnd(() => {if (!this.isEnd) {this.isEnd = truefor (let index = 0; index < 5; index++) {this.num++this.arr.arr.push("Hello" + this.num)}this.isEnd = false}}).width('100%').height("95%").alignListItem(ListItemAlign.Center).scrollBar(BarState.Off)}.onRefreshing(() => {setTimeout(() => {const arr = new Arr().arrthis.arr.arr = arrthis.isRefreshing = false;this.getUIContext().getPromptAction().showToast({ message: "刷新成功" })}, 2000)}).refreshOffset(64).pullToRefresh(true)}}
}
觉得有用,可以点赞或收藏
