使用ForEach组件在点击后如何获得被点击的子组件的索引?

主要代码如下

List() {
        ForEach(this.FarmList, (Farm:FarmBean) => {
          ListItem() {this.FarmListItem(Farm.name, Farm.fieldId)}
          .onClick(()=>{
            //ToDo
          })
        })
      }
      .listDirection(Axis.Vertical)
      .divider({
        strokeWidth: 1,
        startMargin: 60,
        endMargin: 10,
        color: '#a1949494' })
      .scrollBar(BarState.Auto)

在这个循环渲染中,我希望能够在子组件被点击时获取到这个子组件在列表中的索引,从而对子组件实现状态管理。

希望能够解答。


DevEco Studio
UI框架
2024-05-29 13:38:03
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
Oolver
class FarmBean {
  name: string = ""
  fieldId: string = ""

  constructor(name, fieldId) {
    this.name = name
    this.fieldId = fieldId
  }
}

@Entry
@Component
struct test {
  @State FarmList: Array<FarmBean> = [
    new FarmBean('图片1.jpg', "id1"),
    new FarmBean('文本2.txt', "id2")
  ]

  build() {
    Column() {
      List() {
        ForEach(this.FarmList, (Farm: FarmBean, index: number) => {
          ListItem() {
            this.FarmListItem(Farm.name, Farm.fieldId)
          }
          .onClick(() => {
            console.info('====内容:', JSON.stringify(Farm), ",子组件在列表中的索引:" + index)
          })
        })
      }
      .listDirection(Axis.Vertical)
      .divider({
        strokeWidth: 1,
        startMargin: 60,
        endMargin: 10,
        color: '#a1949494' })
      .scrollBar(BarState.Auto)
    }
  }

  @Builder
  FarmListItem(name, fieldId) {
    Text('文件名' + name + ',文件id:' + fieldId).fontSize(20)
  }
}
分享
微博
QQ
微信
回复
2024-05-29 15:46:14
相关问题
组件如何处理组件点击事件
1068浏览 • 1回复 待解决
如何执行点击某个组件命令?
2767浏览 • 1回复 待解决
panel组件点击区域问题
3201浏览 • 1回复 待解决
组件调用组件方法
423浏览 • 1回复 待解决
组件组件使用@Link双向同步
312浏览 • 1回复 待解决
鸿蒙JS UI如何获得当前组件值?
5391浏览 • 1回复 待解决
Scroll组件展示位置如何调整
712浏览 • 1回复 待解决