Skip to content

React 暗夜模式

通过 theme 选项或 ref 上的 setTheme() 显式切换亮色 / 暗色。表格样式基于 .vt-root 上的 --vt-* CSS 变量,暗色下自动套用暗色 token。

除显式切换外,表格处于 .dark 祖先元素下(如 VitePress / Tailwind 暗色)会自动应用暗色,无需手动设置。

使用的 API

ts
type Options = {
  list: T[];  // 数据列表
  itemKey: string;  // 行唯一标识字段名
  estimatedSize: number;  // 行预估高度(px)
  theme?: 'light' | 'dark';  // 初始主题
}

// 实例方法(ref 上调用):运行时切换
tableRef.current?.setTheme('dark');
tableRef.current?.setTheme('light');

完整的主题定制(--vt-* 变量清单、密度变体、行高等式、深浅色作用域)见 Vanilla · 暗夜模式

示例

微应用尚未挂载。

源码

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

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

const ROW_COUNT = 1000;

const columns: ReactTableColumn<Row>[] = [
  { key: 'id', title: 'ID', width: 80, fixed: 'left' },
  { key: 'name', title: '姓名', width: 160 },
  { key: 'email', title: '邮箱', width: 240 },
  { key: 'city', title: '城市', width: 160 },
  { key: 'score', title: '分数', width: 120, align: 'right' },
];

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

export default function ThemeTable() {
  const tableRef = React.useRef<VirtTableRef>(null);
  const [theme, setTheme] = React.useState<'light' | 'dark'>('light');

  return (
    <div className="demo-wrapper">
      <h3 className="demo-title">React 暗夜模式</h3>
      <div className="virt-table-controls">
        <button
          type="button"
          className="virt-table-btn virt-table-btn-primary"
          onClick={() => {
            const next = theme === 'light' ? 'dark' : 'light';
            setTheme(next);
            tableRef.current?.setTheme(next);
          }}
        >
          {theme === 'light' ? '🌙 切换暗夜模式' : '☀️ 切换亮色模式'}
        </button>
        <span className="demo-note">当前:{theme === 'light' ? '亮色' : '暗色'}</span>
      </div>
      <div style={{ width: 760, height: 520 }} className="demo-container">
        <VirtTableReact
          ref={tableRef}
          columns={columns}
          options={{
            list,
            itemKey: 'id',
            estimatedSize: 40,
            buffer: 6,
            border: true,
            stripe: true,
            highlightHoverRow: true,
            theme: 'light',
          }}
        />
      </div>
    </div>
  );
}