Skip to content

React 键盘导航 ​

装载 vtCellSelection() + vtKeyboardNav() 后,先单击单元格再用键盘操作:方向键移动、Tab/Shift+Tab 左右、Enter 下移、F2 进入编辑、Shift+方向键扩展选区。目标行不在视口时会自动滚动。

示例 ​

微应用尚未挂载。

源码 ​

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

interface Row extends Record<string, unknown> {
  id: number;
  name: string;
  age: number;
  city: string;
  score: number;
}

const columns: ReactTableColumn<Row>[] = [
  { key: 'id', title: 'ID', width: 80 },
  { key: 'name', title: '姓名', width: 180 },
  { key: 'age', title: '年龄', width: 120 },
  { key: 'city', title: '城市', width: 180 },
  { key: 'score', title: '分数', width: 120 },
];

const list: Row[] = Array.from({ length: 1000 }, (_, i) => ({
  id: i + 1,
  name: faker.person.fullName(),
  age: faker.number.int({ min: 18, max: 60 }),
  city: faker.location.city(),
  score: faker.number.int({ min: 0, max: 100 }),
}));

export default function KeyboardTable() {
  const plugins = React.useMemo(() => [vtCellSelection(), vtKeyboardNav()], []);

  return (
    <div className="demo-wrapper">
      <h3 className="demo-title">React 键盘导航</h3>
      <div className="demo-hint">
        先单击任一单元格,然后使用键盘:<b>方向键</b> 移动 · <b>Tab / Shift+Tab</b> 左右 ·{' '}
        <b>Enter</b> 下移 · <b>Shift+方向</b> 扩选区
      </div>
      <div style={{ width: 760, height: 480 }} className="demo-container">
        <VirtTableReact
          columns={columns}
          options={{ plugins, list, itemKey: 'id', estimatedSize: 40, buffer: 6, border: true }}
        />
      </div>
    </div>
  );
}

相关 API ​

字段 / 方法作用详见
vtKeyboardNav()键盘导航(requires: vtCellSelection)插件机制 · 键盘导航
完整按键表方向键 / Tab / Enter / Home / End / Ctrl+Home / PageUp / Shift+ / F2插件机制 · 键盘导航
vtCellEditor()装了才响应 F2插件机制

翻一屏 = 视口能放下多少行,按 clientHeight / estimatedSize 估。动态行高下是近似值 —— 差一两行无妨,scrollToCell 会把目标行滚进视口。Mac 上多数键盘没有独立 Home / End 键,所以 Cmd 组合与 Ctrl 等效。

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