在 OpenHarmony(ArkUI,基于 eTS/ArkTS)里,“列表组件”通常指 List + ListItem,或者更现代的 **LazyForEach + ListItem**。
所谓“自定义列表组件”,一般包含 3 个层级:
下面按从简单到进阶给你说明。
@Component
struct MyListItem {
private title: string
private subTitle: string
build() {
ListItem() {
Column() {
Text(this.title)
.fontSize(18)
.fontWeight(FontWeight.Bold)
Text(this.subTitle)
.fontSize(14)
.fontColor('#999')
}
.padding(12)
}
}
}
使用:
List() {
MyListItem({ title: '标题1', subTitle: '副标题1' })
MyListItem({ title: '标题2', subTitle: '副标题2' })
}
interface ItemData {
id: number
title: string
desc: string
}
@Component
struct CustomItem {
@Prop item: ItemData
build() {
ListItem() {
Row() {
Text(this.item.title)
.fontSize(18)
Text(this.item.desc)
.fontSize(14)
.fontColor('#666')
}
.padding(12)
.width('100%')
}
}
}
@Component
export struct CustomList {
@State data: ItemData[] = []
build() {
List() {
ForEach(this.data, (item) => {
CustomItem({ item })
}, item => item.id)
}
.width('100%')
.height('100%')
}
}
适用于 上百/上千条数据。
class MyDataSource extends BasicDataSource<ItemData> {
private list: ItemData[] = []
getData(index: number): ItemData {
return this.list[index]
}
totalCount(): number {
return this.list.length
}
}
List() {
LazyForEach(this.dataSource, (item) => {
CustomItem({ item })
}, item => item.id)
}
ListItem() {
// UI
}
.onClick(() => {
console.log('点击了:', this.item.title)
})
ListItem() {
// UI
}
.swipeAction({
end: {
action: () => {
// 删除逻辑
},
label: '删除'
}
})
List() {
ListItemGroup({
header: Text('分组1')
}) {
MyListItem({ ... })
MyListItem({ ... })
}
}
if (this.data.length === 0) {
Text('暂无数据')
}
✅ 列表项用 @Component 封装
✅ 大数据用 LazyForEach
✅ 数据用 @State / @Link 管理
✅ 列表组件对外只暴露 data 和回调
如果你愿意,可以告诉我:
我可以直接给你一份可运行的完整示例。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。