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

AG Grid React分组场景下,如何获取选中行所在的页码?

获取AG Grid React分组行场景下选中行的页码

在分组行+固定分页大小的场景下,要获取选中行的页码,核心是基于AG Grid的API拿到行在展开后扁平化显示列表中的位置,再结合分页大小计算页码,具体实现如下:

实现步骤

  • 通过AG Grid API获取选中行的RowNode对象
  • 拿到该行在当前展开状态下的显示索引
  • 根据分页大小计算对应的页码

代码示例

假设你已经通过useRef保存了AG Grid的实例引用:

import { useRef } from 'react';
import { AgGridReact } from 'ag-grid-react';

const YourGridComponent = () => {
  const gridApi = useRef(null);
  const PAGE_SIZE = 10;

  // 获取选中行的页码
  const getSelectedRowPages = () => {
    if (!gridApi.current) return [];
    
    const selectedNodes = gridApi.current.getSelectedNodes();
    return selectedNodes.map(node => {
      // 获取该行在展开后显示列表中的索引(从0开始)
      const displayedIndex = gridApi.current.getDisplayedRowIndex(node);
      
      // 若行处于折叠的分组中,会返回-1,这里根据业务处理
      if (displayedIndex === -1) {
        return { rowId: node.data.id, pageNumber: '行未显示(分组折叠)' };
      }
      
      // 计算页码(分页从1开始)
      const pageNumber = Math.floor(displayedIndex / PAGE_SIZE) + 1;
      return { rowId: node.data.id, pageNumber };
    });
  };

  // 监听网格加载完成
  const onGridReady = (params) => {
    gridApi.current = params.api;
    params.api.paginationSetPageSize(PAGE_SIZE);
  };

  // 监听分组展开/折叠,重新计算页码(如果需要实时更新)
  const onRowGroupOpened = () => {
    const pageInfo = getSelectedRowPages();
    console.log('选中行页码更新:', pageInfo);
  };

  return (
    <div className="ag-theme-alpine">
      <AgGridReact
        rowData={yourRowData}
        columnDefs={yourColumnDefs}
        enableRowGroup={true}
        pagination={true}
        paginationPageSize={PAGE_SIZE}
        onGridReady={onGridReady}
        onRowGroupOpened={onRowGroupOpened}
        rowSelection="multiple" // 根据你的选择模式调整
      />
      {/* 比如点击按钮触发获取页码 */}
      <button onClick={() => console.log(getSelectedRowPages())}>
        获取选中行页码
      </button>
    </div>
  );
};

export default YourGridComponent;

关键说明

  1. getDisplayedRowIndex(node):这个API会返回当前展开状态下,该行在所有可见行中的位置,是计算页码的核心。如果行所在的父分组被折叠,会返回-1,需要针对性处理。
  2. 页码计算逻辑:因为分页从第1页开始,所以用Math.floor(索引/分页大小) + 1得到正确页码。
  3. 实时更新:如果需要在分组展开/折叠时自动更新页码,可以监听onRowGroupOpened事件,重新调用计算函数。

内容的提问来源于stack exchange,提问作者Pradhumn Sharma

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 16:44:55