在 OpenHarmony(ArkUI) 中,“列表分组”通常有两种常见实现方式,取决于你使用的是 ArkTS 声明式开发(推荐) 还是 JS/FA 模型。
下面以 ArkTS(API 9+) 为主说明。
List +ListItemGroup 实现分组(推荐)OpenHarmony 原生支持 分组列表,通过 ListItemGroup 来实现。
@Entry
@Component
struct GroupListExample {
build() {
List() {
ListItemGroup({ header: this.groupHeader('分组一') }) {
ListItem() {
Text('item 1-1')
}
ListItem() {
Text('item 1-2')
}
}
ListItemGroup({ header: this.groupHeader('分组二') }) {
ListItem() {
Text('item 2-1')
}
ListItem() {
Text('item 2-2')
}
}
}
.width('100%')
.height('100%')
}
@Builder
groupHeader(title: string) {
Text(title)
.fontSize(20)
.fontWeight(FontWeight.Bold)
.padding(10)
.backgroundColor('#f1f1f1')
.width('100%')
}
}
ListItemGroup 是原生分组容器header 可自定义(Builder)实际开发中,数据通常是结构化的:
interface Group {
title: string
items: string[]
}
@Entry
@Component
struct DataGroupList {
private groups: Group[] = [
{ title: '水果', items: ['苹果', '香蕉'] },
{ title: '蔬菜', items: ['西红柿', '黄瓜'] }
]
build() {
List() {
ForEach(this.groups, (group: Group) => {
ListItemGroup({ header: this.header(group.title) }) {
ForEach(group.items, (item: string) => {
ListItem() {
Text(item)
.padding(10)
}
})
}
})
}
}
@Builder
header(title: string) {
Text(title)
.fontSize(18)
.fontWeight(FontWeight.Bold)
.padding(10)
}
}
如果你不想用 ListItemGroup,也可以:
ForEach 中手动插入“分组标题 Item”ListItem 的样式区分但不推荐,因为:
✅ 推荐使用
ListListItemGroupForEach⚠️ 注意
ListItemGroup 必须放在 List 中header 不是必填,但建议加LazyForEach在 JS 中通常通过:
list + section(部分版本)可以告诉我你使用的 OpenHarmony 版本 / API 等级 / 开发语言(ArkTS / JS),我可以给你更精准的示例。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。