温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

OpenHarmony ListView怎样分页

发布时间:2026-09-19 22:06:44 来源:亿速云 阅读:93 作者:小樊 栏目:软件技术

在 OpenHarmony(ArkUI) 里,并没有像 Android 那样专门的 ListView 控件,而是使用 List 组件 + ForEach / LazyForEach 来实现列表和分页。下面按常见做法给你说明。


一、基础 List 示例(非分页)

@Entry
@Component
struct ListPage {
  @State data: string[] = Array.from({ length: 100 }, (_, i) => `Item ${i}`)

  build() {
    List() {
      ForEach(this.data, (item: string) => {
        ListItem() {
          Text(item)
            .fontSize(20)
            .padding(10)
        }
      })
    }
  }
}

⚠️ 如果数据量很大,ForEach 会一次性渲染,性能不好。


二、推荐做法:LazyForEach + 分页(懒加载)

1️⃣ 实现 DataSource(IDataSource)

class MyDataSource implements IDataSource {
  private list: string[] = []

  totalCount(): number {
    return this.list.length
  }

  getData(index: number): string {
    return this.list[index]
  }

  addData(data: string[]) {
    this.list.push(...data)
  }

  registerDataChangeListener() {}
  unregisterDataChangeListener() {}
}

2️⃣ 页面中使用 LazyForEach 分页加载

@Entry
@Component
struct PagedListPage {
  @State dataSource = new MyDataSource()
  private page = 1
  private pageSize = 20

  aboutToAppear() {
    this.loadMore()
  }

  loadMore() {
    const newData = Array.from(
      { length: this.pageSize },
      (_, i) => `Item ${(this.page - 1) * this.pageSize + i}`
    )
    this.dataSource.addData(newData)
    this.page++
  }

  build() {
    List() {
      LazyForEach(this.dataSource, (item: string) => {
        ListItem() {
          Text(item)
            .fontSize(20)
            .padding(10)
        }
      }, (item: string) => item)
    }
    .onReachEnd(() => {
      this.loadMore()
    })
  }
}

✅ onReachEnd:列表滚动到底部时触发
✅ LazyForEach:只渲染可视区域,性能最好


三、手动“分页按钮”方式(不常用)

Button('加载更多')
  .onClick(() => {
    this.loadMore()
  })

适合不适合滚动加载的场景(如平板、电视)。


四、总结对照

方式 是否推荐 说明
ForEach ❌ 数据多会卡
LazyForEach ✅ 官方推荐
onReachEnd ✅ 自动分页
按钮分页 ⚠️ 特殊场景

如果你用的是 OpenHarmony 3.x / 4.x / 5.x,或者是在 Stage 模型 / FA 模型,我可以给你更精确的示例。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI
助
手