You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ag-grid-react中基于客户端名称实现动态行选择/取消选择

在AG Grid React中实现按客户端名称批量选中行

实现思路

核心是借助Grid API获取行数据,监听选中事件,当首次选中某一行时,自动匹配并选中所有同clientName的行,同时要避免触发循环选中的问题。

具体代码实现

  1. 声明存储Grid实例与控制选中状态的变量
    用useRef保存Grid API实例,再用状态变量标记是否处于批量选中过程,防止循环触发onSelectionChanged:
import { useRef, useState } from 'react';
import { Grid } from 'ag-grid-react';

const MyGridComponent = () => {
  const gridApiRef = useRef(null);
  const [isBatchSelecting, setIsBatchSelecting] = useState(false);
  
  // 你的其他变量(dataset、columnDefs等)
  1. 修改onGridReady保存Grid API
const onGridReady = (params) => {
  gridApiRef.current = params.api;
};
  1. 重写onSelectionChanged处理批量选中逻辑
const getSelectedRowData = () => {
  if (isBatchSelecting) return;
  
  const selectedRows = gridApiRef.current.getSelectedRows();
  // 仅在首次选中1行时触发批量选中
  if (selectedRows.length === 1) {
    const targetClientName = selectedRows[0].clientName;
    
    setIsBatchSelecting(true);
    // 遍历所有行节点,匹配clientName后选中
    gridApiRef.current.forEachNode((node) => {
      if (node.data.clientName === targetClientName) {
        node.setSelected(true);
      }
    });
    setIsBatchSelecting(false);
  }
  
  // 保留你原本获取选中行数据的逻辑
  // ... 你的原有代码
};
  1. 更新Grid组件属性
    将修改后的方法传入Grid,其余属性保持不变:
<Grid
  onGridReady={onGridReady}
  rowData={dataset}
  floatingFilter
  sideBar={GRID_SIDE_BAR}
  onSelectionChanged={getSelectedRowData}
  licenseKey={'test'}
  enableSelect={true}
  rowSelection={'multiple'}
  getRowId={getRowNodeId}
  columnDefs={columnDefs}
  defaultColDef={defaultColDef}
  cacheQuickFilter={true}
/>

关键说明

  • isBatchSelecting状态:标记当前是否在批量选中过程中,避免批量选中后再次触发onSelectionChanged造成无限循环。
  • forEachNode:遍历Grid所有行节点,通过node.data.clientName匹配目标客户端名称,调用node.setSelected(true)完成选中操作。
  • 选中行数量判断:仅在用户首次选中1行时执行批量操作,避免多选场景下重复触发逻辑。

内容的提问来源于stack exchange,提问作者KARTHIKEYAN.A

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 09:47:33