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

React中SyncFusion DataGrid如何获取选中列名称?

SyncFusion DataGrid 获取选中列名称的方法

SyncFusion的DataGrid没有直接对应getSelectedRecords()的内置方法来获取选中列,但可以通过两种简洁方式实现需求:

1. 实时监听列选择事件记录选中列

开启列选择模式后,绑定columnSelected事件,在事件回调中维护本地状态来保存选中列的名称:

import { DataGridComponent } from '@syncfusion/ej2-react-grids';
import { useState } from 'react';

function App() {
  const [selectedColumns, setSelectedColumns] = useState([]);

  const onColumnSelected = (args) => {
    let updatedCols = [...selectedColumns];
    // 根据当前列选中状态更新数组
    if (args.selected) {
      updatedCols.push(args.column.field);
    } else {
      updatedCols = updatedCols.filter(field => field !== args.column.field);
    }
    setSelectedColumns(updatedCols);
  };

  return (
    <DataGridComponent
      dataSource={yourDataSource}
      allowColumnSelection={true}
      columnSelected={onColumnSelected}
      // 其他配置项
    >
      {/* 列定义 */}
    </DataGridComponent>
  );
}

此时selectedColumns数组会实时同步所有选中列的field(即列名称/字段名)。

2. 通过组件实例主动获取选中列

使用ref获取DataGrid实例后,调用内置的getSelectedColumns()方法直接获取选中列对象,再提取名称:

import { DataGridComponent } from '@syncfusion/ej2-react-grids';
import { useRef } from 'react';

function App() {
  const gridRef = useRef(null);

  const fetchSelectedCols = () => {
    if (gridRef.current) {
      // 获取选中列的对象数组
      const selectedColObjects = gridRef.current.getSelectedColumns();
      // 提取列名称(field属性)
      const selectedColNames = selectedColObjects.map(col => col.field);
      console.log(selectedColNames);
    }
  };

  return (
    <>
      <button onClick={fetchSelectedCols}>获取选中列</button>
      <DataGridComponent
        ref={gridRef}
        dataSource={yourDataSource}
        allowColumnSelection={true}
        // 其他配置项
      >
        {/* 列定义 */}
      </DataGridComponent>
    </>
  );
}

补充说明:getSelectedRecords()确实仅用于获取选中行;若需要获取选中单元格,需开启单元格选择模式(selectionSettings={{ type: 'Cell' }}),再调用getSelectedCells()方法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 07:55:01