Skip to content

React 单元格选区 ​

启用单元格选区后,可拖动鼠标选择矩形区域,并通过回调获取选区范围。

示例 ​

微应用尚未挂载。

源码 ​

点击查看源码
tsx
import React from 'react';
import { VirtTableReact, type ReactTableColumn, type VirtTableRef,
  vtCellSelection,
} from '@virt-table/react';
import { faker } from '@faker-js/faker';

const COL_COUNT = 10;
const ROW_COUNT = 500;

const columns: ReactTableColumn[] = Array.from({ length: COL_COUNT }, (_, i) => ({
  key: `extra_${i}`,
  title: `列 ${i}`,
  width: 150,
}));

const list = Array.from({ length: ROW_COUNT }, (_, i) => {
  const row: Record<string, unknown> = { id: i };
  for (let c = 0; c < COL_COUNT; c++) {
    row[`extra_${c}`] = `${i}-${c}-${faker.lorem.word()}`;
  }
  return row;
});

export default function CellSelectionTable() {
  const tableRef = React.useRef<VirtTableRef>(null);
  const [status, setStatus] = React.useState('拖拽选择单元格区域(vtCellSelection 插件)');
  return (
    <div className="demo-wrapper">
      <h3 className="demo-title">React 单元格选区</h3>
      <div className="virt-table-controls" />
      <div className="status-text">{status}</div>
      <div style={{ width: 800, height: 600 }} className="demo-container">
        <VirtTableReact
          ref={tableRef}
          columns={columns}
          options={{
            list,
            itemKey: 'id',
            plugins: [vtCellSelection()],
            estimatedSize: 40,
            buffer: 4,
            border: true,
            onCellSelectionChange: (range) => {
              if (!range) {
                setStatus('选区已清除');
                return;
              }
              setStatus(
                `onCellSelectionChange: (${range.startRow},${range.startCol}) → (${range.endRow},${range.endCol})`,
              );
            },
          }}
        />
      </div>
    </div>
  );
}

相关 API ​

字段 / 方法作用详见
vtCellSelection()框选插件插件机制
onCellSelectionChange选区变化回调 { startRow, startCol, endRow, endCol } | null表格配置
getCellSelection / clearCellSelection读写选区实例方法

选区会按合并块扩张成完整矩形,见按值自动合并。

全量字段见 表格配置 / 列配置 / 实例方法。

上面的字段在 React 端原样透传(实例方法通过组件 ref 调用)。封装层特有的部分 —— 组件 Props、渲染函数返回 JSX、ref 转发了哪些方法 —— 见 React API。