React Kendo Grid行双击事件实现:如何获取对应行数据?
解决React Kendo Grid双击行获取行数据的问题
我来帮你搞定这个双击行拿数据的问题~你现在的思路是对的,但直接操作DOM绑定事件的话,确实容易遇到拿不到数据以及数据更新后事件失效的问题,这里给你两种可行的方案:
方案一:改进DOM绑定,通过UID获取行数据
Kendo Grid渲染的每一行<tr>元素都会自带一个data-uid属性,这个属性和数据源中对应数据项的uid是一一对应的。你可以利用这个关联关系,从数据源中找到对应的行数据:
componentDidMount() { this.bindDoubleClickEvents(); } // 新增componentDidUpdate,处理数据更新后重新绑定事件 componentDidUpdate(prevProps) { // 当数据源变化时重新绑定 if (prevProps.dataSource !== this.props.dataSource) { this.bindDoubleClickEvents(); } } bindDoubleClickEvents() { const { onDoubleClick, dataSource } = this.props; if (!onDoubleClick || !dataSource) return; const gridElement = document.querySelector('.k-widget.k-grid'); if (!gridElement) return; // 先移除旧的事件绑定,避免重复绑定 const existingRows = gridElement.querySelectorAll('.k-grid-table tbody tr'); existingRows.forEach(row => { row.removeEventListener('dblclick', this.handleRowDoubleClick); }); // 绑定新的双击事件 const rows = gridElement.querySelectorAll('.k-grid-table tbody tr'); rows.forEach(row => { row.addEventListener('dblclick', this.handleRowDoubleClick); }); } handleRowDoubleClick = (e) => { const { onDoubleClick, dataSource } = this.props; const uid = e.currentTarget.getAttribute('data-uid'); const rowData = dataSource.getByUid(uid); onDoubleClick(rowData); }
这里额外处理了componentDidUpdate,因为当Grid的数据分页、筛选或者更新时,之前渲染的行会被替换,需要重新绑定事件;同时先移除旧绑定避免重复触发。
方案二:使用Grid的rowRender属性(推荐)
这种方式更符合React的组件化思想,不需要手动操作DOM,直接通过Grid提供的rowRender自定义行渲染,给每行添加双击事件:
<Grid dataSource={this.props.dataSource} // 其他Grid配置项... rowRender={(rowProps) => { return ( <tr {...rowProps.props} // 直接拿到当前行的dataItem onDoubleClick={() => this.props.onDoubleClick(rowProps.dataItem)} > {rowProps.children} </tr> ); }} />
这种方案的优势很明显:
- 不需要手动处理DOM的事件绑定与解绑
- 数据更新时,Grid会自动重新渲染行,双击事件也会自动同步
- 直接通过
rowProps.dataItem拿到行数据,不需要额外的UID匹配逻辑
如果你用的是新版的Kendo React Grid(比如基于函数组件的版本),写法类似,只是把rowRender换成对应的自定义渲染属性即可。
内容的提问来源于stack exchange,提问作者Zied Hf
相关产品推荐
相关产品推荐

