温馨提示×

温馨提示×

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

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

如何自定义OpenHarmony列表组件

发布时间:2026-09-01 07:46:12 来源:亿速云 阅读:94 作者:小樊 栏目:软件技术

在 OpenHarmony(ArkUI,基于 eTS/ArkTS)里,“列表组件”通常指 List + ListItem,或者更现代的 **LazyForEach + ListItem**。
所谓“自定义列表组件”,一般包含 3 个层级:

  1. 自定义列表项(ListItem)
  2. 自定义列表布局与交互(List)
  3. 封装成可复用组件(@Component)

下面按从简单到进阶给你说明。


一、最基础的自定义列表项

@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' })
}

二、自定义完整列表组件(推荐方式)

1️⃣ 定义数据模型

interface ItemData {
  id: number
  title: string
  desc: string
}

2️⃣ 自定义列表项组件

@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%')
    }
  }
}

3️⃣ 自定义列表组件

@Component
export struct CustomList {
  @State data: ItemData[] = []

  build() {
    List() {
      ForEach(this.data, (item) => {
        CustomItem({ item })
      }, item => item.id)
    }
    .width('100%')
    .height('100%')
  }
}

三、使用 LazyForEach(大数据量必备)

适用于 上百/上千条数据。

1️⃣ 实现 DataSource

class MyDataSource extends BasicDataSource<ItemData> {
  private list: ItemData[] = []

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

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

2️⃣ 列表使用

List() {
  LazyForEach(this.dataSource, (item) => {
    CustomItem({ item })
  }, item => item.id)
}

四、自定义交互(点击 / 滑动)

点击事件

ListItem() {
  // UI
}
.onClick(() => {
  console.log('点击了:', this.item.title)
})

滑动删除(SwipeToDelete)

ListItem() {
  // UI
}
.swipeAction({
  end: {
    action: () => {
      // 删除逻辑
    },
    label: '删除'
  }
})

五、常见自定义需求示例

✅ 分组列表

List() {
  ListItemGroup({
    header: Text('分组1')
  }) {
    MyListItem({ ... })
    MyListItem({ ... })
  }
}

✅ 空状态

if (this.data.length === 0) {
  Text('暂无数据')
}

六、最佳实践建议

✅ 列表项用 @Component 封装
✅ 大数据用 LazyForEach
✅ 数据用 @State / @Link 管理
✅ 列表组件对外只暴露 data 和回调


如果你愿意,可以告诉我:

  • API 版本(如 OpenHarmony 3.2 / 4.0)
  • 是 Stage 模型还是 FA 模型
  • 想要“卡片式 / 聊天式 / 瀑布流”哪种列表

我可以直接给你一份可运行的完整示例。

向AI问一下细节

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

AI
助
手