如何获取Container中被点击组件所在行的索引?最优方案
最优实现方案
在ExtJS中要实现点击行内任意组件获取行索引,最简洁高效的思路是利用事件冒泡+行容器自定义属性/实时索引查找,下面给你具体实现方式:
方法一:创建行时存储固定索引(适合行不会动态排序/删除的场景)
这种方式性能最优,因为不需要每次点击都去查找索引,直接从行容器上读取预先存储的值:
addFilter: function (token, filter, op) { // 先将配置存入数组,此时新元素的索引就是数组长度-1 this.tokenValues.push(this.config); const rowIndex = this.tokenValues.length - 1; const filterItem = Ext.create({ xtype: 'container', height: 30, cls: 'purge-filter-item', layout: { type: 'hbox', align: 'middle' }, // 自定义属性存储行的创建索引 rowIndex: rowIndex, listeners: { // 监听行容器的click事件,子组件点击会冒泡到这里 click: function (rowContainer) { console.log('当前行索引:', rowContainer.rowIndex); // 这里可以直接使用rowIndex做后续逻辑处理 }, scope: this // 保持回调函数的作用域为当前组件 }, items: [ // 你的子组件内容,比如输入框、按钮等 { xtype: 'textfield', fieldLabel: '筛选条件' }, { xtype: 'button', text: '删除' } // ...其他子组件 ] }); // 将行容器添加到父容器中(假设父容器是this.filterContainer) this.filterContainer.add(filterItem); }
方法二:实时查找行在父容器中的索引(适合行可能被动态删除/排序的场景)
如果你的行可能会被删除、调整顺序,那么预先存储的索引会失效,这时候可以通过父容器的items.indexOf()方法实时获取当前行的索引:
addFilter: function (token, filter, op) { this.tokenValues.push(this.config); const filterItem = Ext.create({ xtype: 'container', height: 30, cls: 'purge-filter-item', layout: { type: 'hbox', align: 'middle' }, listeners: { click: function (rowContainer) { // 获取存放所有行的父容器 const parentContainer = rowContainer.up('container'); // 实时查找当前行在父容器中的索引 const currentRowIndex = parentContainer.items.indexOf(rowContainer); console.log('当前行实时索引:', currentRowIndex); }, scope: this }, items: [ // 你的子组件内容 ] }); this.filterContainer.add(filterItem); }
核心优势说明
- 事件冒泡复用:只需要给行容器绑定一次
click事件,行内所有子组件的点击都会冒泡到行容器触发回调,不需要给每个子组件单独加监听,代码更简洁,性能更优。 - 两种方案适配不同场景:固定索引适合静态列表,实时查找适合动态变化的列表,你可以根据业务需求选择。
内容的提问来源于stack exchange,提问作者user1234
相关产品推荐
相关产品推荐

