温馨提示×

温馨提示×

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

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

OpenHarmony列表组件如何多选

发布时间:2026-09-01 08:10:11 来源:亿速云 阅读:89 作者:小樊 栏目:软件技术

在 OpenHarmony(ArkUI) 中,列表组件(如 List + ListItem)本身没有内置的多选模式,多选通常是通过状态管理 + 交互逻辑来实现的。下面按常见场景给你说明。


一、基础思路(核心原理)

  1. 用一个 状态集合 保存被选中的项(如 Set<string> 或 Array<string>)
  2. 给每个 ListItem 增加 选中状态
  3. 点击时切换选中状态
  4. 根据选中状态改变 UI(勾选框、背景色等)

二、简单示例(List 多选)

1️⃣ 页面结构

@Entry
@Component
struct MultiSelectList {
  @State selectedItems: Set<number> = new Set()
  private dataList: number[] = [1, 2, 3, 4, 5]

  toggleSelect(item: number) {
    if (this.selectedItems.has(item)) {
      this.selectedItems.delete(item)
    } else {
      this.selectedItems.add(item)
    }
  }

  build() {
    Column() {
      List() {
        ForEach(this.dataList, (item: number) => {
          ListItem() {
            Row() {
              Text(`Item ${item}`)
              if (this.selectedItems.has(item)) {
                Text('✔')
              }
            }
            .width('100%')
            .padding(10)
            .backgroundColor(
              this.selectedItems.has(item) ? '#d0ebff' : '#ffffff'
            )
            .onClick(() => this.toggleSelect(item))
          }
        })
      }
    }
  }
}

✅ 点击即可多选
✅ 再次点击取消


三、带 CheckBox 的多选(更规范)

ListItem() {
  Row() {
    Checkbox({ name: item.toString() })
      .select(this.selectedItems.has(item))
      .onChange((isSelected) => {
        if (isSelected) {
          this.selectedItems.add(item)
        } else {
          this.selectedItems.delete(item)
        }
      })
    Text(`Item ${item}`)
  }
}

四、全选 / 反选

@State allSelected: boolean = false

selectAll() {
  this.selectedItems = new Set(this.dataList)
}

clearAll() {
  this.selectedItems.clear()
}

五、获取选中结果

console.log([...this.selectedItems])

六、注意事项

  • ✅ Set 比 Array 更适合多选(去重、查找快)
  • ✅ 大数据列表建议配合 LazyForEach
  • ✅ 如果是 编辑模式,可加一个“编辑/完成”按钮控制是否可多选

如果你用的是 eTS / ArkTS 版本、API 9 / 10 / 11,或者想要 左滑删除 + 多选 的示例,我可以给你更具体的代码。

向AI问一下细节

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

AI
助
手