Feature-rich and customizable data grid React component
| 文件 | 最后提交记录 | 最后更新时间 |
|---|---|---|
| 1 天前 | ||
| 9 天前 | ||
| 7 天前 | ||
| 1 天前 | ||
| 8 天前 | ||
| 6 年前 | ||
| 1 天前 | ||
| 6 个月前 | ||
| 7 天前 | ||
| 9 天前 | ||
| 11 个月前 | ||
| 9 天前 | ||
| 11 个月前 | ||
| 9 天前 | ||
| 4 天前 | ||
| 1 年前 | ||
| 1 天前 | ||
| 1 天前 | ||
| 4 天前 | ||
| 4 个月前 | ||
| 4 天前 | ||
| 5 个月前 | ||
| 5 个月前 | ||
| 5 个月前 | ||
| 5 个月前 | ||
| 4 天前 | ||
| 1 天前 |
react-data-grid
DataGrid 组件旨在高效处理大型数据集,同时提供丰富的自定义与交互功能。
目录
特性
- React 19.2+ 支持
- 常青浏览器和服务端渲染支持
- 支持 Tree-shaking,且无外部依赖,保持打包产物精简
- 得益于虚拟化,性能表现优秀:视口外的列和行不会被渲染
- 使用 TypeScript 进行严格类型标注
- 键盘可访问性
- 通过
color-scheme开箱即支持浅色模式和深色模式。 - 冻结列:冻结列,使其在水平滚动时保持可见。
- 列宽调整
- 多列排序
- 点击可排序的列标题,可在升序和降序之间切换
- Ctrl+点击 / Meta+点击 可对额外列进行排序
- 列合并
- 列分组
- 行选择
- 行分组
- 汇总行
- 动态行高
- 无行回退
- 单元格格式化
- 单元格编辑
- 单元格复制 / 粘贴
- 单元格值拖拽 / 填充
- 可自定义渲染器
- 支持从右到左(RTL)。
链接
安装
使用您喜欢的包管理器安装 react-data-grid:
npm i react-data-grid
pnpm add react-data-grid
yarn add react-data-grid
bun add react-data-grid
此外,请在应用中导入默认样式:
import 'react-data-grid/lib/styles.css';
react-data-grid 以 ECMAScript 模块形式发布,支持常青浏览器、打包器以及服务端渲染。
重要
Vite 8+ 默认使用lightningcss来压缩 css,但该库在压缩 light-dark 语法时存在一个 bug。你可以调整cssMinify或cssTarget的设置作为替代方案。
build: {
cssMinify: 'esbuild',
// or
cssTarget: 'esnext'
}
快速开始
以下是在 React 应用中使用 react-data-grid 的基本示例:
import 'react-data-grid/lib/styles.css';
import { DataGrid, type Column } from 'react-data-grid';
interface Row {
id: number;
title: string;
}
const columns: readonly Column<Row>[] = [
{ key: 'id', name: 'ID' },
{ key: 'title', name: 'Title' }
];
const rows: readonly Row[] = [
{ id: 0, title: 'Example' },
{ id: 1, title: 'Demo' }
];
function App() {
return <DataGrid columns={columns} rows={rows} />;
}
样式与自定义
DataGrid 提供多种方式来定制其外观与行为。
浅色/深色主题
DataGrid 开箱即用即可支持浅色和深色配色方案,借助 light-dark() CSS 函数实现。当设置 color-scheme: light dark; 时,主题将根据用户的系统偏好自动适配。
若要强制应用特定主题,建议在 :root 上设置标准的 color-scheme CSS 属性:
:root {
color-scheme: light; /* or 'dark', or 'light dark' for auto */
}
此外,你也可以为单个表格添加 rdg-light 或 rdg-dark 类:
// Force light theme
<DataGrid className="rdg-light" columns={columns} rows={rows} />
// Force dark theme
<DataGrid className="rdg-dark" columns={columns} rows={rows} />
CSS 变量
DataGrid 支持以下 CSS 变量用于自定义:
.rdg {
/* Selection */
--rdg-selection-width: 2px;
--rdg-selection-color: hsl(207, 75%, 66%);
/* Typography */
--rdg-font-size: 14px;
/* Colors (using light-dark() for automatic theme switching) */
--rdg-color: light-dark(#000, #ddd);
--rdg-background-color: light-dark(hsl(0deg 0% 100%), hsl(0deg 0% 13%));
/* Header */
--rdg-header-background-color: light-dark(hsl(0deg 0% 97.5%), hsl(0deg 0% 10.5%));
--rdg-header-draggable-background-color: light-dark(hsl(0deg 0% 90.5%), hsl(0deg 0% 17.5%));
/* Rows */
--rdg-row-hover-background-color: light-dark(hsl(0deg 0% 96%), hsl(0deg 0% 9%));
--rdg-row-selected-background-color: light-dark(hsl(207deg 76% 92%), hsl(207deg 76% 42%));
--rdg-row-selected-hover-background-color: light-dark(hsl(207deg 76% 88%), hsl(207deg 76% 38%));
/* Borders */
--rdg-border-width: 1px;
--rdg-border-color: light-dark(#ddd, #444);
--rdg-summary-border-width: calc(var(--rdg-border-width) * 2);
--rdg-summary-border-color: light-dark(#aaa, #555);
/* Checkboxes */
--rdg-checkbox-focus-color: hsl(207deg 100% 69%);
}
自定义颜色的示例:
.my-custom-grid {
--rdg-background-color: #f0f0f0;
--rdg-selection-color: #ff6b6b;
--rdg-font-size: 16px;
}
<DataGrid className="my-custom-grid" columns={columns} rows={rows} />
标准 Props
DataGrid 支持标准的 className 和 style 属性:
<DataGrid
columns={columns}
rows={rows}
className="my-grid custom-theme"
style={{ width: 800, height: 600 }}
/>
行与单元格样式
行高
使用 rowHeight、headerRowHeight 和 summaryRowHeight 属性控制行高。rowHeight 属性支持固定高度和按行动态高度。
行类
使用 rowClass 属性为行应用自定义 CSS 类,使用 headerRowClass 属性为表头行应用自定义 CSS 类。
单元格类
使用列定义中的 cellClass 属性为单元格应用自定义 CSS 类。你还可以分别为表头单元格和汇总单元格使用 headerCellClass 和 summaryCellClass。
列宽
使用列定义中的 width、minWidth 和 maxWidth 属性控制列宽。使用 resizable 属性启用列宽调整,或使用 defaultColumnOptions 将其应用于所有列。
自定义渲染器
使用 renderers 属性,以自定义实现替换默认组件。列还可以通过 renderCell、renderHeaderCell、renderSummaryCell、renderGroupCell 和 renderEditCell 属性设置自定义渲染器。
API 参考
组件
<DataGrid />
DataGridProps
columns: readonly ColumnOrColumnGroup<R, SR>[]
列定义和/或列组的数组。有关所有可用选项,请参阅 ColumnOrColumnGroup 类型。
⚠️ 性能: 传入新的 columns 数组会触发整个网格的重新渲染和重新计算。请使用 useMemo 对该属性进行记忆化,或将其定义在组件外部,以避免不必要的重新渲染。
rows: readonly R[]
行数组,行数据可以是任意类型。
💡 性能: 网格针对高效渲染进行了优化:
-
虚拟化:仅将可见行渲染到 DOM 中
-
单行更新:行组件已进行记忆化,因此更新单个行对象只会重新渲染该特定行,而不是所有行
-
数组引用很重要:更改数组引用本身(例如
setRows([...rows]))会触发视口和布局重新计算,即使行对象未发生变化 -
最佳实践:更新行时,创建新数组但复用未变化的行对象。例如:
// ✅ 良好:仅重新渲染发生变化的行 setRows(rows.map((row, idx) => (idx === targetIdx ? { ...row, updated: true } : row))); // ❌ 避免:为所有行创建新引用,导致所有可见行重新渲染 setRows(rows.map((row) => ({ ...row })));
ref?: Maybe<React.Ref<DataGridHandle>>
可选的 ref,用于滚动到某个单元格或聚焦某个单元格等命令式 API。请参阅 DataGridHandle。
topSummaryRows?: Maybe<readonly SR[]>
固定显示在网格顶部的汇总行。
bottomSummaryRows?: Maybe<readonly SR[]>
固定显示在网格底部的汇总行。
rowKeyGetter?: Maybe<(row: R) => K>
用于返回每行唯一键/标识符的函数。要使行选择功能正常工作,必须提供 rowKeyGetter。
import { DataGrid } from 'react-data-grid';
interface Row {
id: number;
name: string;
}
function rowKeyGetter(row: Row) {
return row.id;
}
function MyGrid() {
return <DataGrid columns={columns} rows={rows} rowKeyGetter={rowKeyGetter} />;
}
💡 虽然可选,但建议设置此 prop 以获得最佳性能,因为返回的值会用于设置行元素上的 key prop。
⚠️ 性能: 在组件外部定义此函数,或使用 useCallback 对其进行记忆化,以避免不必要的重新渲染。
onRowsChange?: Maybe<(rows: R[], data: RowsChangeData<R, SR>) => void>
当行发生变化时触发的回调。
第一个参数是一个新的行数组,其中包含已更新的行以及其他未更改的行。
第二个参数是一个对象,其中包含 indexes 数组,通过索引标明发生变化的行,以及 column 表示变化发生的列。
import { useState } from 'react';
import { DataGrid } from 'react-data-grid';
function MyGrid() {
const [rows, setRows] = useState(initialRows);
return <DataGrid columns={columns} rows={rows} onRowsChange={setRows} />;
}
rowHeight?: Maybe<number | ((row: R) => number)>
默认值: 35 像素
每一行的高度(像素)。可使用函数设置不同的行高。
// Fixed height for all rows
<DataGrid columns={columns} rows={rows} rowHeight={50} />;
// Dynamic height per row
function getRowHeight(row) {
return row.isExpanded ? 100 : 35;
}
<DataGrid columns={columns} rows={rows} rowHeight={getRowHeight} />;
⚠️ 性能: 使用函数时,所有行的高度都会被提前处理。对于大型数据集(1000+ 行),如果函数引用发生变化并使内部记忆化失效,可能会引发性能问题。在可能的情况下,建议使用静态函数,或对 rowHeight 函数进行记忆化。
headerRowHeight?: Maybe<number>
默认值: 当 rowHeight 是数字时使用 rowHeight,否则为 35 像素
表头行高度,单位为像素。
summaryRowHeight?: Maybe<number>
默认值: 当 rowHeight 是数字时使用 rowHeight,否则为 35 像素
每个汇总行的高度,单位为像素。
<DataGrid
columns={columns}
rows={rows}
rowHeight={35}
headerRowHeight={45}
summaryRowHeight={40}
topSummaryRows={topSummaryRows}
/>
columnWidths?: Maybe<ColumnWidths>
列宽映射,包含实测宽度和调整后的宽度。若未提供,则使用内部状态。
const [columnWidths, setColumnWidths] = useState((): ColumnWidths => new Map());
function addNewRow() {
setRows(...);
// reset column widths after adding a new row
setColumnWidths(new Map());
}
return <DataGrid columnWidths={columnWidths} onColumnWidthsChange={setColumnWidths} ... />
onColumnWidthsChange?: Maybe<(columnWidths: ColumnWidths) => void>
当列宽发生变化时触发的回调。若未提供,则使用内部状态。
selectedRows?: Maybe<ReadonlySet<K>>
一组已选中的行键。要使行选择生效,需要提供 rowKeyGetter。
isRowSelectionDisabled?: Maybe<(row: NoInfer<R>) => boolean>
用于确定特定行是否禁用行选择的函数。
onSelectedRowsChange?: Maybe<(selectedRows: Set<K>) => void>
当选择状态发生变化时触发的回调。
import { useState } from 'react';
import { DataGrid, SelectColumn } from 'react-data-grid';
const rows: readonly Row[] = [...];
const columns: readonly Column<Row>[] = [
SelectColumn,
// other columns
];
function rowKeyGetter(row: Row) {
return row.id;
}
function isRowSelectionDisabled(row: Row) {
return !row.isActive;
}
function MyGrid() {
const [selectedRows, setSelectedRows] = useState((): ReadonlySet<number> => new Set());
return (
<DataGrid
rowKeyGetter={rowKeyGetter}
columns={columns}
rows={rows}
selectedRows={selectedRows}
isRowSelectionDisabled={isRowSelectionDisabled}
onSelectedRowsChange={setSelectedRows}
/>
);
}
sortColumns?: Maybe<readonly SortColumn[]>
已排序列数组。
排序为受控模式:数据表格不会替你重新排列 rows。请基于 sortColumns 对 rows 状态(或派生行)应用排序。
onSortColumnsChange?: Maybe<(sortColumns: SortColumn[]) => void>
排序发生变化时触发的回调。
import { useState } from 'react';
import { DataGrid, SelectColumn } from 'react-data-grid';
const rows: readonly Row[] = [...];
const columns: readonly Column<Row>[] = [
{
key: 'name',
name: 'Name',
sortable: true
},
// other columns
];
function MyGrid() {
const [sortColumns, setSortColumns] = useState<readonly SortColumn[]>([]);
return (
<DataGrid
columns={columns}
rows={rows}
sortColumns={sortColumns}
onSortColumnsChange={setSortColumns}
/>
);
}
可以通过 ctrl (command) + click 对多列进行排序。若要禁用多列排序,请将 onSortColumnsChange 函数更改为
function onSortColumnsChange(sortColumns: SortColumn[]) {
setSortColumns(sortColumns.slice(-1));
}
defaultColumnOptions?: Maybe<DefaultColumnOptions<R, SR>>
应用于所有列的默认选项。
function MyGrid() {
return (
<DataGrid
columns={columns}
rows={rows}
defaultColumnOptions={{
minWidth: 100,
resizable: true,
sortable: true,
draggable: true
}}
/>
);
}
onCellMouseDown?: CellMouseEventHandler<R, SR>
当指针在单元格上激活时触发的回调。默认行为是聚焦该单元格。调用 preventGridDefault 可阻止默认行为。
function onCellMouseDown(args: CellMouseArgs<R, SR>, event: CellMouseEvent) {
if (args.column.key === 'id') {
event.preventGridDefault();
}
}
<DataGrid rows={rows} columns={columns} onCellMouseDown={onCellMouseDown} />;
onCellClick?: CellMouseEventHandler<R, SR>
单元格被点击时触发的回调函数。
function onCellClick(args: CellMouseArgs<R, SR>, event: CellMouseEvent) {
if (args.column.key === 'id') {
event.preventGridDefault();
}
}
<DataGrid rows={rows} columns={columns} onCellClick={onCellClick} />;
此事件可用于在单击时打开单元格编辑器。
function onCellClick(args: CellMouseArgs<R, SR>, event: CellMouseEvent) {
if (args.column.key === 'id') {
args.setActivePosition(true);
}
}
onCellDoubleClick?: CellMouseEventHandler<R, SR>
当单元格被双击时触发的回调。若单元格可编辑,默认行为为打开编辑器。调用 preventGridDefault 可阻止默认行为。
function onCellDoubleClick(args: CellMouseArgs<R, SR>, event: CellMouseEvent) {
if (args.column.key === 'id') {
event.preventGridDefault();
}
}
<DataGrid rows={rows} columns={columns} onCellDoubleClick={onCellDoubleClick} />;
onCellContextMenu?: CellMouseEventHandler<R, SR>
单元格被右键单击时触发的回调函数。
function onCellContextMenu(args: CellMouseArgs<R, SR>, event: CellMouseEvent) {
if (args.column.key === 'id') {
event.preventDefault();
// open custom context menu
}
}
<DataGrid rows={rows} columns={columns} onCellContextMenu={onCellContextMenu} />;
onCellKeyDown?: Maybe<(args: CellKeyDownArgs<R, SR>, event: CellKeyboardEvent) => void>
在单元格的 keydown 事件被触发时调用的函数。该事件可用于自定义单元格的导航和编辑行为。
示例
- 防止按下
Enter时进入编辑
function onCellKeyDown(args: CellKeyDownArgs<R, SR>, event: CellKeyboardEvent) {
if (args.mode === 'ACTIVE' && event.key === 'Enter') {
event.preventGridDefault();
}
}
- 阻止按
Tab键时进行导航
function onCellKeyDown(args: CellKeyDownArgs<R, SR>, event: CellKeyboardEvent) {
if (args.mode === 'ACTIVE' && event.key === 'Tab') {
event.preventGridDefault();
}
}
查看更多示例
onCellCopy?: Maybe<(args: CellCopyArgs<NoInfer<R>, NoInfer<SR>>, event: CellClipboardEvent) => void>
当单元格内容被复制时触发的回调。
onCellPaste?: Maybe<(args: CellPasteArgs<NoInfer<R>, NoInfer<SR>>, event: CellClipboardEvent) => R>
当内容粘贴到单元格时触发的回调。
返回更新后的行;数据网格会携带该行调用 onRowsChange。
onActivePositionChange?: Maybe<(args: PositionChangeArgs<R, SR>) => void>
当活动位置发生变化时触发。
请参阅下方“类型”部分中的 PositionChangeArgs 类型。
onFill?: Maybe<(event: FillEvent<R>) => R>
onScroll?: React.UIEventHandler<HTMLDivElement> | undefined
原生 DOM onScroll 属性。
onColumnResize?: Maybe<(column: CalculatedColumn<R, SR>, width: number) => void>
当列宽被调整时触发的回调。
onColumnsReorder?: Maybe<(sourceColumnKey: string, targetColumnKey: string) => void>
当列重新排序时触发的回调。
enableVirtualization?: Maybe<boolean>
默认值: true
可通过此属性禁用虚拟化。
renderers?: Maybe<Renderers<R, SR>>
用于单元格、行及其他组件的自定义渲染器。
请参阅 Renderers 类型查看完整结构。
替换默认组件的示例:
import { DataGrid, type Renderers } from 'react-data-grid';
const customRenderers: Renderers<Row, SummaryRow> = {
// Custom row render function
renderRow(key, props) {
return <CustomRow key={key} {...props} />;
},
// Custom cell render function
renderCell(key, props) {
return <CustomCell key={key} {...props} />;
},
// Custom checkbox render function
renderCheckbox(props) {
return <CustomCheckbox {...props} />;
},
// Custom sort status indicator
renderSortStatus(props) {
return <CustomSortIcon {...props} />;
},
// Custom empty state
noRowsFallback: <div>No data available</div>
};
<DataGrid columns={columns} rows={rows} renderers={customRenderers} />;
默认的 <Row /> 组件可以通过 renderRow 属性进行包装,以添加上下文或调整属性:
import { DataGrid, Row, type RenderRowProps } from 'react-data-grid';
interface MyRow {
id: number;
}
function myRowRenderer(key: React.Key, props: RenderRowProps<MyRow>) {
return (
<MyContext key={key} value={123}>
<Row {...props} />
</MyContext>
);
}
function MyGrid() {
return <DataGrid columns={columns} rows={rows} renderers={{ renderRow: myRowRenderer }} />;
}
rowClass?: Maybe<(row: R, rowIdx: number) => Maybe<string>>
用于为行应用自定义类名的函数。
import { DataGrid } from 'react-data-grid';
function rowClass(row: Row, rowIdx: number) {
return rowIdx % 2 === 0 ? 'even' : 'odd';
}
function MyGrid() {
return <DataGrid columns={columns} rows={rows} rowClass={rowClass} />;
}
⚠️ 性能: 将此函数定义在组件外部,或使用 useCallback 进行记忆化,以避免在每次渲染时重新渲染所有行。
headerRowClass?: Maybe<string>
表头行的自定义类名。
<DataGrid columns={columns} rows={rows} headerRowClass="sticky-header" />
direction?: Maybe<'ltr' | 'rtl'>
该属性用于设置网格的文本方向,默认值为 'ltr'(从左到右)。将 direction 设置为 'rtl' 会产生以下效果:
- 列从右向左排列
- 起始冻结列固定于右侧,结束冻结列固定于左侧
- 列宽调整光标显示在列的左侧边缘
- 滚动条移动至左侧
className?: string | undefined
网格的自定义类名。
style?: CSSProperties | undefined
网格的自定义样式。
role?: string | undefined
网格容器的 ARIA 角色。默认值为 grid。
'aria-label'?: string | undefined
网格的标签。建议使用 aria-label 或 aria-labelledby 提供标签。
'aria-labelledby'?: string | undefined
包含网格标签的元素的 id。建议使用 aria-label 或 aria-labelledby 提供标签。
'aria-rowcount'?: number | undefined
辅助技术使用的总行数。
'aria-description'?: string | undefined
'aria-describedby'?: string | undefined
如果网格具有标题或描述,可以在网格元素上设置 aria-describedby,其值指向包含描述内容的元素。
'data-testid'?: Maybe<string>
此属性可用于添加测试用的 testid。建议通过 role 和 name 查询网格。
function MyGrid() {
return <DataGrid aria-label="my-grid" columns={columns} rows={rows} />;
}
test('grid', async () => {
await page.render(<MyGrid />);
const grid = page.getByRole('grid', { name: 'my-grid' });
});
'data-cy'?: Maybe<string>
可选属性,便于 Cypress(或类似工具)选择器使用。
<TreeDataGrid />
TreeDataGrid 是一个基于 DataGrid 构建的组件,用于增加层级行分组。它实现了 Treegrid 模式。
工作原理:
groupBy属性指定用于分组的列rowGrouper函数按指定的列键对行进行分组- 分组行会渲染展开/折叠切换控件
- 子行嵌套在其父级分组下
- 可通过点击切换按钮,或使用键盘导航(←、→)展开/折叠分组
键盘导航:
- →(右方向键):聚焦已折叠的分组行时,将其展开
- ←(左方向键):聚焦已展开的分组行时,将其折叠,或导航到父级分组
不支持的属性:
以下 DataGrid 属性在 TreeDataGrid 中不受支持:
onFill- 树形数据网格中已禁用拖动填充isRowSelectionDisabled- 不支持禁用行选择role-TreeDataGrid管理 ARIA 角色aria-rowcount-TreeDataGrid管理 ARIA 行数
注意事项:
- 分组列无法渲染在同一列下
- 分组列会自动冻结,且无法取消冻结
- 分组行不支持单元格复制/粘贴
- 不支持列组;
columns必须为Column[]
TreeDataGridProps
除上述列出的属性外,DataGridProps 中的所有属性均受支持。columns 属性仅支持 Column[](不支持列组)。当 rowHeight 为函数时,它会接收 RowHeightArgs,而不是仅接收行。额外属性如下:
groupBy: readonly string[]
必填。 用于分组的列键数组。顺序决定分组层级(第一个键为顶层,第二个键嵌套在第一个键下,依此类推)。
import { TreeDataGrid, type Column } from 'react-data-grid';
interface Row {
id: number;
country: string;
city: string;
name: string;
}
const columns: readonly Column<Row>[] = [
{ key: 'country', name: 'Country' },
{ key: 'city', name: 'City' },
{ key: 'name', name: 'Name' }
];
function MyGrid() {
return (
<TreeDataGrid
columns={columns}
rows={rows}
groupBy={['country', 'city']}
// ... other props
/>
);
}
rowGrouper: (rows: readonly R[], columnKey: string) => Record<string, readonly R[]>
必填。 一个按指定列键对行进行分组的函数。返回一个对象,其中键为分组值,值为属于该分组的行数组。
function rowGrouper(rows: readonly Row[], columnKey: string): Record<string, readonly Row[]> {
return Object.groupBy(rows, (row) => row[columnKey]);
}
expandedGroupIds: ReadonlySet<unknown>
必填。 当前已展开的分组 ID 集合。分组 ID 由 groupIdGetter 生成。
import { useState } from 'react';
import { TreeDataGrid } from 'react-data-grid';
function MyGrid() {
const [expandedGroupIds, setExpandedGroupIds] = useState((): ReadonlySet<unknown> => new Set());
return (
<TreeDataGrid
expandedGroupIds={expandedGroupIds}
onExpandedGroupIdsChange={setExpandedGroupIds}
// ... other props
/>
);
}
onExpandedGroupIdsChange: (expandedGroupIds: Set<unknown>) => void
必填。 分组展开或折叠时触发的回调。
groupIdGetter?: Maybe<(groupKey: string, parentId?: string) => string>
用于生成分组行唯一标识的函数。若未提供,则采用默认实现,以 __ 拼接父级 key 与分组 key。
rowHeight?: Maybe<number | ((args: RowHeightArgs<R>) => number)>
注意: 与 DataGrid 不同,rowHeight 函数会接收 RowHeightArgs<R>,其中包含 type 属性,用于区分普通行与分组行:
function getRowHeight(args: RowHeightArgs<Row>): number {
if (args.type === 'GROUP') {
return 50; // Custom height for group rows
}
return 35; // Height for regular rows
}
<TreeDataGrid rowHeight={getRowHeight} ... />
<Row />
默认行组件。可通过 renderers.renderRow 属性进行包装。
Props
RenderRowProps<TRow, TSummaryRow>
<Cell />
默认单元格组件。可通过 renderers.renderCell 属性进行包装。
Props
CellRendererProps<TRow, TSummaryRow>
<SelectCellFormatter />
用于渲染行选择复选框的格式化组件。
Props
value: boolean
复选框是否选中。
tabIndex?: number | undefined
用于键盘导航的 Tab 索引。
indeterminate?: boolean | undefined
复选框是否处于不确定状态。
disabled?: boolean | undefined
复选框是否禁用。
onChange: (checked: boolean, shift: boolean) => void
复选框状态发生变化时的回调。
'aria-label'?: string | undefined
复选框的无障碍标签。
'aria-labelledby'?: string | undefined
为复选框提供标签的元素的 ID。
<ToggleGroup />
供 renderToggleGroup 使用的底层组件,用于渲染展开/折叠控件。在构建自定义分组单元格渲染器时很有用。
Hooks
useHeaderRowSelection()
用于管理表头行选择状态的 Hook。在自定义表头单元格渲染器内使用,以实现自定义的“全选”功能。
返回值:
isIndeterminate: boolean- 部分(而非全部)行已选中isRowSelected: boolean- 所有行均已选中onRowSelectionChange: (event: SelectHeaderRowEvent) => void- 用于更改选择状态的回调
示例:
import { useLayoutEffect, useRef } from 'react';
function CustomHeaderCell() {
const { isIndeterminate, isRowSelected, onRowSelectionChange } = useHeaderRowSelection();
const checkboxRef = useRef<HTMLInputElement>(null);
useLayoutEffect(() => {
if (checkboxRef.current) {
checkboxRef.current.indeterminate = isIndeterminate && !isRowSelected;
}
}, [isIndeterminate, isRowSelected]);
return (
<input
ref={checkboxRef}
type="checkbox"
checked={isRowSelected}
onChange={(event) => onRowSelectionChange({ checked: event.target.checked })}
/>
);
}
useRowSelection()
用于管理行选择状态的 Hook。可在自定义单元格渲染器中使用,以实现自定义行选择。
返回:
isRowSelectionDisabled: boolean- 是否禁用该行选择isRowSelected: boolean- 该行是否已选中onRowSelectionChange: (event: SelectRowEvent<R>) => void- 用于更改选择状态的回调
示例:
function CustomSelectCell({ row }: RenderCellProps<Row>) {
const { isRowSelectionDisabled, isRowSelected, onRowSelectionChange } = useRowSelection();
return (
<input
type="checkbox"
disabled={isRowSelectionDisabled}
checked={isRowSelected}
onChange={(event) =>
onRowSelectionChange({
row,
checked: event.currentTarget.checked,
isShiftClick: event.nativeEvent.shiftKey
})
}
/>
);
}
渲染函数
renderHeaderCell<R, SR>(props: RenderHeaderCellProps<R, SR>)
默认表头单元格渲染器。渲染可排序列,并显示排序指示器。
示例:
import { renderHeaderCell, type Column } from 'react-data-grid';
const columns: readonly Column<Row>[] = [
{
key: 'name',
name: 'Name',
sortable: true,
renderHeaderCell
}
];
renderTextEditor<TRow, TSummaryRow>(props: RenderEditCellProps<TRow, TSummaryRow>)
为方便使用而提供的基础文本编辑器。
示例:
import { renderTextEditor, type Column } from 'react-data-grid';
const columns: readonly Column<Row>[] = [
{
key: 'title',
name: 'Title',
renderEditCell: renderTextEditor
}
];
renderSortIcon(props: RenderSortIconProps)
渲染排序方向箭头图标。
Props:
sortDirection: SortDirection | undefined- 'ASC'、'DESC' 或 undefined
renderSortPriority(props: RenderSortPriorityProps)
渲染多列排序中的排序优先级编号。
Props:
priority: number | undefined- 排序优先级(1、2、3 等)
renderCheckbox(props: RenderCheckboxProps)
渲染具有规范样式与可访问性的复选框输入。
Props:
checked: boolean- 复选框是否已选中indeterminate?: boolean- 复选框是否处于不确定状态disabled?: boolean- 复选框是否已禁用onChange: (checked: boolean, shift: boolean) => void- 变更处理函数tabIndex: number- 用于键盘导航的制表索引aria-label?: string- 可访问性标签aria-labelledby?: string- 标签元素的 ID
示例:
import { DataGrid, renderCheckbox } from 'react-data-grid';
<DataGrid
renderers={{
renderCheckbox: (props) => renderCheckbox({ ...props, 'aria-label': 'Select row' })
}}
/>;
renderToggleGroup<R, SR>(props: RenderGroupCellProps<R, SR>)
由 groupBy prop 指定的分组列所使用的默认分组单元格渲染器。它会渲染展开/收起切换控件。
Props
RenderGroupCellProps<TRow, TSummaryRow>
示例:
import { renderToggleGroup, type Column } from 'react-data-grid';
const columns: readonly Column<Row>[] = [
{
key: 'group',
name: 'Group',
renderGroupCell: renderToggleGroup
}
];
renderValue<R, SR>(props: RenderCellProps<R, SR>)
默认单元格渲染器,用于渲染 row[column.key] 的值。
示例:
import { renderValue, type Column } from 'react-data-grid';
const columns: readonly Column<Row>[] = [
{
key: 'title',
name: 'Title',
renderCell: renderValue
}
];
上下文
DataGridDefaultRenderersContext
该上下文用于为应用中的 DataGrid 提供默认渲染器。
示例:
import {
DataGridDefaultRenderersContext,
renderCheckbox,
renderSortIcon,
renderSortPriority,
type Renderers
} from 'react-data-grid';
// custom implementations of renderers
const defaultGridRenderers: Renderers<unknown, unknown> = {
renderCheckbox,
renderSortStatus(props) {
return (
<>
{renderSortIcon(props)}
{renderSortPriority(props)}
</>
);
}
};
function AppProvider({ children }) {
return (
<DataGridDefaultRenderersContext value={defaultGridRenderers}>
{children}
</DataGridDefaultRenderersContext>
);
}
其他
SelectColumn: Column<any, any>
预配置的行选择列。 包含表头、普通行和分组行的复选框渲染器。
示例:
import { DataGrid, SelectColumn, type Column } from 'react-data-grid';
const columns: readonly Column<Row>[] = [SelectColumn, ...otherColumns];
function rowKeyGetter(row: Row) {
return row.id;
}
function MyGrid() {
return (
<DataGrid
columns={columns}
rows={rows}
rowKeyGetter={rowKeyGetter}
selectedRows={selectedRows}
onSelectedRowsChange={setSelectedRows}
/>
);
}
SELECT_COLUMN_KEY = 'rdg-select-column'
SelectColumn 所使用的键名,可用于识别或筛选选择列。
示例:
import { SELECT_COLUMN_KEY } from 'react-data-grid';
const nonSelectColumns = columns.filter((column) => column.key !== SELECT_COLUMN_KEY);
类型
Column<TRow, TSummaryRow>
定义网格中一列的配置。
name: string | ReactElement
列名称。默认显示在表头单元格中。
key: string
用于区分每一列的唯一键
width?: Maybe<number | string>
默认 auto
宽度可以是任何有效的 css grid 列值。如果未指定,将根据网格宽度以及其他列的指定宽度自动确定。
const columns: Column<Row>[] = [
{
key: 'id',
name: 'ID',
width: 80, // Fixed width in pixels
resizable: false
},
{
key: 'name',
name: 'Name',
width: '30%', // Percentage width
minWidth: 100,
maxWidth: 400
},
{
key: 'description',
name: 'Description'
// No width specified - automatically sized
}
];
其他示例:
width: 80, // pixels
width: '25%',
width: 'max-content',
width: 'minmax(100px, max-content)',
max-content 可用于扩展列,以显示全部内容。注意,网格仅能针对可见行计算列宽。
minWidth?: Maybe<number>
默认值:50 像素
最小列宽(像素)。
maxWidth?: Maybe<number>
最大列宽(像素)。
cellClass?: Maybe<string | ((row: TRow) => Maybe<string>)>
单元格的类名。可以是字符串,也可以是一个函数,用于根据行返回类名。
const columns: Column<Row>[] = [
{
key: 'status',
name: 'Status',
cellClass: (row) => `status-${row.status}`
},
{
key: 'price',
name: 'Price',
cellClass: 'text-right' // Static class
}
];
.status-active {
color: green;
font-weight: bold;
}
.status-inactive {
color: grey;
}
.text-right {
text-align: right;
}
headerCellClass?: Maybe<string>
表头单元格的类名(可多个)。
summaryCellClass?: Maybe<string | ((row: TSummaryRow) => Maybe<string>)>
汇总单元格的类名(可多个)。可以是字符串,也可以是返回类名的函数,该函数会根据汇总行返回类名。
renderCell?: Maybe<(props: RenderCellProps<TRow, TSummaryRow>) => ReactNode>
用于渲染单元格内容的渲染函数。
renderHeaderCell?: Maybe<(props: RenderHeaderCellProps<TRow, TSummaryRow>) => ReactNode>
用于渲染表头单元格内容的渲染函数。
renderSummaryCell?: Maybe<(props: RenderSummaryCellProps<TSummaryRow, TRow>) => ReactNode>
用于渲染汇总单元格内容的渲染函数。
renderGroupCell?: Maybe<(props: RenderGroupCellProps<TRow, TSummaryRow>) => ReactNode>
当使用 TreeDataGrid 时,用于渲染分组单元格内容的渲染函数。
renderEditCell?: Maybe<(props: RenderEditCellProps<TRow, TSummaryRow>) => ReactNode>
用于渲染编辑单元格内容的渲染函数。设置后,该列会自动变为可编辑状态。
editable?: Maybe<boolean | ((row: TRow) => boolean)>
控制单元格是否可通过 renderEditCell 进行编辑。
colSpan?: Maybe<(args: ColSpanArgs<TRow, TSummaryRow>) => Maybe<number>>
用于确定该单元格应跨多少列的函数。返回跨列数,或返回 undefined 表示不跨列。请参阅下方“类型”部分中的 ColSpanArgs 类型。
示例:
import type { Column } from 'react-data-grid';
const columns: readonly Column<Row>[] = [
{
key: 'title',
name: 'Title',
colSpan(args) {
if (args.type === 'ROW' && args.row.isFullWidth) {
return 5; // Span 5 columns for full-width rows
}
return undefined;
}
}
];
frozen?: Maybe<boolean | 'start' | 'end'>
默认值: false
决定该列是否冻结,以及冻结在哪一侧。冻结的列在网格水平滚动时会保持固定位置。
'start'(或为向后兼容使用true)— 将列固定在起始边缘(LTR 中为左侧,RTL 中为右侧)。'end'— 将列固定在结束边缘(LTR 中为右侧,RTL 中为左侧)。false(默认)— 该列随网格其余部分一起滚动。
const columns: readonly Column<Row>[] = [
{ key: 'id', name: 'ID', frozen: 'start' },
{ key: 'name', name: 'Name' },
{ key: 'actions', name: 'Actions', frozen: 'end' }
];
resizable?: Maybe<boolean>
默认值: false
启用列宽调整
sortable?: Maybe<boolean>
默认值: false
启用列排序
draggable?: Maybe<boolean>
默认值: false
启用列拖拽
sortDescendingFirst?: Maybe<boolean>
默认值: false
设置列首次排序时的方向为降序,而非升序
editorOptions
单元格编辑选项。
displayCellContent?: Maybe<boolean>
默认值: false
在编辑单元格内容之外,同时渲染原始单元格内容。当编辑器在网格外部渲染时(例如在弹窗中),请启用此选项。
commitOnOutsideClick?: Maybe<boolean>
默认值: true
点击单元格外部时提交更改。
closeOnExternalRowChange?: Maybe<boolean>
默认值: true
当行数据在外部发生变化时关闭编辑器。
ColumnGroup<TRow, TSummaryRow>
定义共享同一表头的一组列。
interface ColumnGroup<R, SR = unknown> {
readonly name: string | ReactElement;
readonly headerCellClass?: Maybe<string>;
readonly children: readonly ColumnOrColumnGroup<R, SR>[];
}
示例:
import type { ColumnOrColumnGroup } from 'react-data-grid';
const columns: readonly ColumnOrColumnGroup<Row>[] = [
{
name: 'Personal Info',
children: [
{ key: 'firstName', name: 'First Name' },
{ key: 'lastName', name: 'Last Name' }
]
}
];
ColumnOrColumnGroup<TRow, TSummaryRow>
表示 Column 或 ColumnGroup 的联合类型。
CalculatedColumn<TRow, TSummaryRow>
在 Column 基础上扩展了表格内部使用的额外计算属性。这是传递给渲染函数的类型。
额外属性:
idx: number- 列索引level: number- 使用列组时的嵌套层级parent: CalculatedColumnParent | undefined- 若为嵌套列,则为父级列组- 多个 Column 属性的值已被设置为默认值
CalculatedColumnParent<TRow, TSummaryRow>
表示计算列结构中的父级列组。
interface CalculatedColumnParent<R, SR> {
readonly name: string | ReactElement;
readonly parent: CalculatedColumnParent<R, SR> | undefined;
readonly idx: number;
readonly colSpan: number;
readonly level: number;
readonly headerCellClass?: Maybe<string>;
}
CalculatedColumnOrColumnGroup<TRow, TSummaryRow>
一个联合类型,表示 CalculatedColumnParent 或 CalculatedColumn 之一。
type CalculatedColumnOrColumnGroup<R, SR> = CalculatedColumnParent<R, SR> | CalculatedColumn<R, SR>;
RowHeightArgs<TRow>
当 TreeDataGrid 的 rowHeight prop 为函数时,传递给它的参数。
type RowHeightArgs<TRow> = { type: 'ROW'; row: TRow } | { type: 'GROUP'; row: GroupRow<TRow> };
示例:
function getRowHeight(args: RowHeightArgs<Row>): number {
if (args.type === 'GROUP') {
return 40;
}
return args.row.isLarge ? 60 : 35;
}
<TreeDataGrid rowHeight={getRowHeight} ... />
RenderCellProps<TRow, TSummaryRow>
传递给自定义单元格渲染器的 Props。
interface RenderCellProps<TRow, TSummaryRow = unknown> {
column: CalculatedColumn<TRow, TSummaryRow>;
row: TRow;
rowIdx: number;
isCellEditable: boolean;
tabIndex: number;
onRowChange: (row: TRow) => void;
}
示例:
import type { RenderCellProps } from 'react-data-grid';
function renderCell({ row, column, onRowChange }: RenderCellProps<MyRow>) {
return (
<div>
{row[column.key]}
<button onClick={() => onRowChange({ ...row, updated: true })}>Update</button>
</div>
);
}
RenderHeaderCellProps<TRow, TSummaryRow>
传递给自定义表头单元格渲染器的属性。
interface RenderHeaderCellProps<TRow, TSummaryRow = unknown> {
column: CalculatedColumn<TRow, TSummaryRow>;
sortDirection: SortDirection | undefined;
priority: number | undefined;
tabIndex: number;
}
RenderEditCellProps<TRow, TSummaryRow>
传递给自定义编辑单元格渲染器(编辑器)的属性。
interface RenderEditCellProps<TRow, TSummaryRow = unknown> {
column: CalculatedColumn<TRow, TSummaryRow>;
row: TRow;
rowIdx: number;
onRowChange: (row: TRow, commitChanges?: boolean) => void;
onClose: (commitChanges?: boolean, shouldFocus?: boolean) => void;
}
示例:
import type { RenderEditCellProps } from 'react-data-grid';
function CustomEditor({ row, column, onRowChange, onClose }: RenderEditCellProps<MyRow>) {
return (
<input
autoFocus
value={row[column.key]}
onChange={(event) => onRowChange({ ...row, [column.key]: event.target.value })}
onBlur={() => onClose(true)}
/>
);
}
RenderSummaryCellProps<TSummaryRow, TRow>
传递给汇总单元格渲染器的 Props。
interface RenderSummaryCellProps<TSummaryRow, TRow = unknown> {
column: CalculatedColumn<TRow, TSummaryRow>;
row: TSummaryRow;
tabIndex: number;
}
RenderGroupCellProps<TRow, TSummaryRow>
使用 TreeDataGrid 时传递给分组单元格渲染器的 Props。
interface RenderGroupCellProps<TRow, TSummaryRow = unknown> {
groupKey: unknown;
column: CalculatedColumn<TRow, TSummaryRow>;
row: GroupRow<TRow>;
childRows: readonly TRow[];
isExpanded: boolean;
tabIndex: number;
toggleGroup: () => void;
}
RenderRowProps<TRow, TSummaryRow>
传递给自定义行渲染器的 Props。
interface RenderRowProps<TRow, TSummaryRow = unknown> {
row: TRow;
iterateOverViewportColumnsForRow: IterateOverViewportColumnsForRow<TRow, TSummaryRow>;
rowIdx: number;
activeCellIdx: number | undefined;
isRowSelectionDisabled: boolean;
isRowSelected: boolean;
gridRowStart: number;
draggedOverCellIdx: number | undefined;
activeCellEditor: ReactElement<RenderEditCellProps<TRow>> | undefined;
onRowChange: (column: CalculatedColumn<TRow, TSummaryRow>, rowIdx: number, newRow: TRow) => void;
rowClass: Maybe<(row: TRow, rowIdx: number) => Maybe<string>>;
isTreeGrid: boolean;
// ... and event handlers
}
CellRendererProps<TRow, TSummaryRow>
使用 renderers.renderCell 时,传递给单元格渲染器的 Props。
它与行渲染 Props 共享基础类型(DOM props 和单元格事件处理器),但仅包含与单元格相关的字段,例如 column、row、rowIdx、colSpan 以及位置状态。
Renderers<TRow, TSummaryRow>
网格的自定义渲染器配置。
interface Renderers<TRow, TSummaryRow> {
renderCell?: Maybe<(key: Key, props: CellRendererProps<TRow, TSummaryRow>) => ReactNode>;
renderCheckbox?: Maybe<(props: RenderCheckboxProps) => ReactNode>;
renderRow?: Maybe<(key: Key, props: RenderRowProps<TRow, TSummaryRow>) => ReactNode>;
renderSortStatus?: Maybe<(props: RenderSortStatusProps) => ReactNode>;
noRowsFallback?: Maybe<ReactNode>;
}
CellMouseArgs<TRow, TSummaryRow>
用于单元格鼠标事件处理程序的参数。
interface CellMouseArgs<TRow, TSummaryRow = unknown> {
/** The column object of the cell. */
column: CalculatedColumn<TRow, TSummaryRow>;
/** The row object of the cell. */
row: TRow;
/** The row index of the cell. */
rowIdx: number;
/** Function to manually focus the cell. Pass `true` to immediately start editing. */
setActivePosition: (enableEditor?: boolean) => void;
}
示例:
import type { CellMouseArgs, CellMouseEvent } from 'react-data-grid';
function onCellClick(args: CellMouseArgs<Row>, event: CellMouseEvent) {
console.log('Clicked cell at row', args.rowIdx, 'column', args.column.key);
args.setActivePosition(true); // Focus and start editing
}
CellMouseEventHandler<TRow, TSummaryRow>(内部)
onCellMouseDown、onCellClick、onCellDoubleClick 和 onCellContextMenu 使用的处理函数类型。该辅助类型未导出,此处仅展示其结构以供参考。
type CellMouseEventHandler<TRow, TSummaryRow> = Maybe<
(args: CellMouseArgs<TRow, TSummaryRow>, event: CellMouseEvent) => void
>;
CellMouseEvent
在 React.MouseEvent<HTMLDivElement> 基础上扩展了网格特有的方法。
event.preventGridDefault(): void
阻止当前事件的网格默认行为。
event.isGridDefaultPrevented(): boolean
返回是否已调用 preventGridDefault。
示例:
import type { CellMouseArgs, CellMouseEvent } from 'react-data-grid';
function onCellClick(args: CellMouseArgs<Row>, event: CellMouseEvent) {
if (args.column.key === 'actions') {
event.preventGridDefault(); // Prevent cell focus
}
}
CellKeyboardEvent
在 React.KeyboardEvent<HTMLDivElement> 基础上扩展了网格相关方法。
event.preventGridDefault(): void
阻止此键盘事件触发网格默认行为。
event.isGridDefaultPrevented(): boolean
返回是否已调用 preventGridDefault。
CellClipboardEvent
React.ClipboardEvent<HTMLDivElement> 的类型别名,用于复制和粘贴事件。
type CellClipboardEvent = React.ClipboardEvent<HTMLDivElement>;
CellKeyDownArgs<TRow, TSummaryRow>
传递给 onCellKeyDown 处理函数的参数。其具体结构取决于单元格当前处于 ACTIVE 还是 EDIT 模式。
ACTIVE 模式:
interface ActiveCellKeyDownArgs<TRow, TSummaryRow = unknown> {
mode: 'ACTIVE';
column: CalculatedColumn<TRow, TSummaryRow> | undefined;
row: TRow | undefined;
rowIdx: number;
setActivePosition: (position: Position, options?: SetActivePositionOptions) => void;
}
编辑模式:
interface EditCellKeyDownArgs<TRow, TSummaryRow = unknown> {
mode: 'EDIT';
column: CalculatedColumn<TRow, TSummaryRow>;
row: TRow;
rowIdx: number;
navigate: () => void;
onClose: (commitChanges?: boolean, shouldFocus?: boolean) => void;
}
示例:
import type { CellKeyboardEvent, CellKeyDownArgs } from 'react-data-grid';
function onCellKeyDown(args: CellKeyDownArgs<Row>, event: CellKeyboardEvent) {
if (args.mode === 'EDIT' && event.key === 'Escape') {
args.onClose(false); // Close without committing
event.preventGridDefault();
}
}
PositionChangeArgs<TRow, TSummaryRow>
传递给 onActivePositionChange 的参数。
interface PositionChangeArgs<TRow, TSummaryRow = unknown> {
/** row index of the active position */
rowIdx: number;
/**
* row object of the active position,
* undefined if the active position is on a header or summary row
*/
row: TRow | undefined;
/**
* column object of the active position,
* undefined if the active position is a row instead of a cell
*/
column: CalculatedColumn<TRow, TSummaryRow> | undefined;
}
CellCopyArgs<TRow, TSummaryRow>
传递给 onCellCopy 的参数。
interface CellCopyArgs<TRow, TSummaryRow = unknown> {
column: CalculatedColumn<TRow, TSummaryRow>;
row: TRow;
}
CellPasteArgs<TRow, TSummaryRow>
传递给 onCellPaste 的参数。
interface CellPasteArgs<TRow, TSummaryRow = unknown> {
column: CalculatedColumn<TRow, TSummaryRow>;
row: TRow;
}
ColSpanArgs<TRow, TSummaryRow>
传递给 colSpan 函数的参数。
type ColSpanArgs<TRow, TSummaryRow> =
| { readonly type: 'HEADER' }
| { readonly type: 'ROW'; readonly row: TRow }
| { readonly type: 'SUMMARY'; readonly row: TSummaryRow };
示例:
import type { Column } from 'react-data-grid';
const columns: readonly Column<Row>[] = [
{
key: 'title',
name: 'Title',
colSpan(args) {
if (args.type === 'ROW' && args.row.isFullWidth) {
return 3; // Span 3 columns
}
return undefined;
}
}
];
SortColumn
描述已排序的列。
interface SortColumn {
readonly columnKey: string;
readonly direction: SortDirection;
}
SortDirection
type SortDirection = 'ASC' | 'DESC';
RowsChangeData<TRow, TSummaryRow>
提供给 onRowsChange 回调的数据。
interface RowsChangeData<R, SR = unknown> {
indexes: number[];
column: CalculatedColumn<R, SR>;
}
indexes: 已更改的行索引数组column: 发生更改的列
SelectRowEvent<TRow>
行选择变更事件对象。
interface SelectRowEvent<TRow> {
row: TRow;
checked: boolean;
isShiftClick: boolean;
}
SelectHeaderRowEvent
表头行选择变更的事件对象。
interface SelectHeaderRowEvent {
checked: boolean;
}
FillEvent<TRow>
用于拖拽填充操作的事件对象。
interface FillEvent<TRow> {
columnKey: string;
sourceRow: TRow;
targetRow: TRow;
}
配合 onFill 属性使用,以处理单元格值的拖拽。
GroupRow<TRow>(内部)
表示 TreeDataGrid 中的分组行。此辅助类型未导出;此处仅展示其类型结构以供参考。
interface GroupRow<TRow> {
readonly childRows: readonly TRow[];
readonly id: string;
readonly parentId: unknown;
readonly groupKey: unknown;
readonly isExpanded: boolean;
readonly level: number;
readonly posInSet: number;
readonly setSize: number;
readonly startRowIndex: number;
}
ColumnWidths
列宽映射。
type ColumnWidths = ReadonlyMap<string, ColumnWidth>;
interface ColumnWidth {
readonly type: 'resized' | 'measured';
readonly width: number;
}
与 columnWidths 和 onColumnWidthsChange props 配合使用,用于从外部控制列宽。
Position
表示网格中单元格的位置。
interface Position {
readonly idx: number; // Column index
readonly rowIdx: number; // Row index
}
SetActivePositionOptions
用于以编程方式更新网格活动位置的选项。
interface SetActivePositionOptions {
enableEditor?: Maybe<boolean>;
shouldFocus?: Maybe<boolean>;
}
RenderCheckboxProps
自定义复选框渲染器的属性。
interface RenderCheckboxProps {
checked: boolean;
indeterminate?: boolean;
disabled?: boolean;
onChange: (checked: boolean, shift: boolean) => void;
tabIndex: number;
'aria-label'?: string;
'aria-labelledby'?: string;
}
RenderSortStatusProps
自定义排序状态渲染器的 Props。
interface RenderSortStatusProps {
sortDirection: SortDirection | undefined;
priority: number | undefined;
}
RenderSortIconProps
自定义排序图标渲染器的属性。
interface RenderSortIconProps {
sortDirection: SortDirection | undefined;
}
RenderSortPriorityProps
用于自定义排序优先级渲染器的 Props。
interface RenderSortPriorityProps {
priority: number | undefined;
}
DataGridHandle
分配给网格 ref 的句柄类型,用于以编程方式控制网格。
interface DataGridHandle {
element: HTMLDivElement | null;
scrollToCell: (position: PartialPosition) => void;
setActivePosition: (position: Position, options?: SetActivePositionOptions) => void;
}
示例:
import { useRef } from 'react';
import { DataGrid, DataGridHandle } from 'react-data-grid';
function MyGrid() {
const gridRef = useRef<DataGridHandle>(null);
function scrollToTop() {
gridRef.current?.scrollToCell({ rowIdx: 0 });
}
return <DataGrid ref={gridRef} columns={columns} rows={rows} />;
}
DefaultColumnOptions<TRow, TSummaryRow>
应用于所有列的默认选项。
type DefaultColumnOptions<TRow, TSummaryRow> = Pick<
Column<TRow, TSummaryRow>,
| 'renderCell'
| 'renderHeaderCell'
| 'width'
| 'minWidth'
| 'maxWidth'
| 'resizable'
| 'sortable'
| 'draggable'
>;
Direction
网格布局的双向性。
type Direction = 'ltr' | 'rtl';
Maybe<T>(内部)
用于可选值的工具类型。此辅助类型未导出;此处展示其结构以供参考。
type Maybe<T> = T | undefined | null;
泛型
R、TRow:行类型SR、TSummaryRow:汇总行类型K:行键类型