KendoUI Grid & React:如何限制网格仅能选中单一行(跨页生效)
解决KendoUI Grid React跨页仅允许选中一行的问题
我懂你的需求——默认开启persistSelection: true后,Grid会保留所有页面的选中行,但你需要全局仅保留一个选中项,不管切换到哪一页。下面是具体的解决方案:
关键调整步骤
确保数据源配置唯一标识
首先要保证你的dataSource的model设置了id字段,这是persistSelection正常工作的基础,它依赖唯一键来跟踪选中状态:const dataSource = new kendo.data.DataSource({ // 其他配置... model: { id: "你的唯一键字段名", // 比如"id"、"productId"等 // 其他model配置 } });修正selectable配置
将selectable明确设置为"single row",确保单页内只能选中一行:selectable: "single row"在change事件中强制控制选中数量
核心逻辑是在change事件触发时,检查当前选中的键列表,如果长度超过1,只保留最后选中的那一项,覆盖之前的选中状态:change: (e) => { const grid = e.sender; const selectedKeys = grid.selectedKeyNames(); // 如果选中的数量大于1,仅保留最后一个选中项 if (selectedKeys.length > 1) { grid.selectedKeyNames([selectedKeys.at(-1)]); } // 这里可以保留你原来的逻辑,比如获取选中的键 console.log(grid.selectedKeyNames()); }
修改后的完整Grid配置
<Grid {...{ dataSource: dataSource, sortable: sortable, selectable: "single row", // 明确设置单页单行选中 scrollable: false, navigatable: true, filterable: filterable, allowCopy: allowCopy, pageable: pageable, perPage: perPage, editable: editable, change: (e) => { const grid = e.sender; const selectedKeys = grid.selectedKeyNames(); if (selectedKeys.length > 1) { grid.selectedKeyNames([selectedKeys.at(-1)]); } // 这里可以添加你的业务逻辑,比如处理选中的键 console.log(grid.selectedKeyNames()); }, persistSelection: true, columns: [ { template: "<span class='sl-select-check'></span>", attributes: { class: 'sl-select-check-td' } }, ...columns ] }} />
原理说明
persistSelection: true会在本地存储中保存所有选中行的唯一键,我们通过selectedKeyNames方法直接修改这个存储的列表,只保留最后选中的项。selectable: "single row"限制单页内的选中行为,配合change事件的全局控制,就能实现跨页仅保留一个选中项的需求。
内容的提问来源于stack exchange,提问作者Zied Hf
相关产品推荐
相关产品推荐

