React VtSwitch 开关
开关列。值语义与交互模型和 VtCheckbox 完全一致(共用同一套真值判定与写回),差别只在外观:一个轨道 + 一个滑块,可以另配开 / 关文案。
示例
微应用尚未挂载。
源码
点击查看源码
tsx
import React from 'react';
import { VirtTableReact, type ReactTableColumn } from '@virt-table/react';
import { VtSwitch } from '@virt-table/vanilla/components';
const ROW_COUNT = 5000;
const list = Array.from({ length: ROW_COUNT }, (_, i) => ({
id: i,
name: `条目 ${i}`,
enabled: i % 2 === 0,
notify: i % 3 === 0,
mode: i % 4 === 0 ? 'on' : 'off',
locked: i % 5 === 0,
}));
export default function VtSwitchTable() {
const [lastChange, setLastChange] = React.useState('(未操作)');
// 计数要在写回后重算,用一个递增的 tick 触发重渲染
const [, bump] = React.useReducer((x: number) => x + 1, 0);
// 列在建表时被捕获一次,onChange 里只能碰 setState —— 所以列定义放进 useMemo
const columns = React.useMemo<ReactTableColumn[]>(
() => [
{ key: 'id', title: 'ID', width: 80, align: 'center' },
{ key: 'name', title: '名称', width: 160 },
VtSwitch({
key: 'enabled',
title: '启用',
width: 110,
onChange: (v, row) => {
setLastChange(`${(row as { name: string }).name} → ${v}`);
bump();
},
}),
// 带文案
VtSwitch({ key: 'notify', title: '通知', width: 160, activeText: '已开启', inactiveText: '已关闭' }),
// 字符串枚举
VtSwitch({
key: 'mode',
title: '模式',
width: 150,
trueValue: 'on',
falseValue: 'off',
activeText: 'on',
inactiveText: 'off',
}),
VtSwitch({ key: 'locked', title: '锁定(只读)', width: 130, disabled: true }),
],
[],
);
const on = list.filter((r) => r.enabled).length;
return (
<div className="demo-wrapper">
<h3 className="demo-title">React VtSwitch 开关</h3>
<div className="status-text">
VtSwitch:点一下即写回,与 VtCheckbox 同一套值语义(trueValue / falseValue)。启用 {on} 行 ·
最近一次 onChange:{lastChange}
</div>
<div style={{ width: 840, height: 600 }} className="demo-container">
<VirtTableReact
columns={columns}
options={{ list, itemKey: 'id', estimatedSize: 40, buffer: 4, border: true }}
/>
</div>
</div>
);
}说明
「直接可点」类组件:点一下就写回,不提供 renderEditor,也不需要 vtCellEditor 插件。
用字符串枚举时必须显式配 trueValue
不配就退回 JS 真值判断,'off' 这种非空字符串会被判成真。
用 <button role="switch"> 而不是 <input type="checkbox">:轨道 + 滑块要两层元素才画得出来,而 input 不能有子节点(伪元素能凑出来,但拿不到 aria-checked 那种明确的状态表达,读屏也读不出「开关」这个角色)。
相关 API
| 字段 | 作用 |
|---|---|
trueValue / falseValue | 写回的值,默认 true / false |
activeText / inactiveText | 开 / 关文案,不配就不画 |
全量选项表见 单元格组件;公共选项 (
placeholder/disabled/clearable/onChange)、asCell()、三类交互模型见 同页上方;列的通用字段见 列配置。上面的字段在 React 端原样透传(实例方法通过组件
ref调用)。封装层特有的部分 —— 组件 Props、渲染函数返回 JSX、ref转发了哪些方法 —— 见 React API。