Skip to content

React VtCheckbox 布尔勾选 ​

布尔列:单元格里直接画一个可点的勾选框。

示例 ​

微应用尚未挂载。

源码 ​

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

const ROW_COUNT = 5000;

const columns: ReactTableColumn[] = [
  { key: 'id', title: 'ID', width: 80, align: 'center' },
  { key: 'name', title: '名称', width: 160 },
  VtCheckbox({ key: 'enabled', title: '启用', width: 100, align: 'center' }),
  // 值不是布尔:勾选写回 'Y'、取消写回 'N'
  VtCheckbox({ key: 'vip', title: 'VIP', width: 100, align: 'center', trueValue: 'Y', falseValue: 'N' }),
  // 数字 1/0
  VtCheckbox({ key: 'audited', title: '已审核', width: 110, align: 'center', trueValue: 1, falseValue: 0 }),
  // 只读回显
  VtCheckbox({ key: 'locked', title: '锁定(只读)', width: 130, align: 'center', disabled: true }),
];

const list = Array.from({ length: ROW_COUNT }, (_, i) => ({
  id: i,
  name: `条目 ${i}`,
  enabled: i % 2 === 0,
  vip: i % 3 === 0 ? 'Y' : 'N',
  audited: i % 4 === 0 ? 1 : 0,
  locked: i % 5 === 0,
}));

const describe = (): string => {
  const on = list.filter((r) => r.enabled).length;
  const vip = list.filter((r) => r.vip === 'Y').length;
  return `VtCheckbox:点一下即写回(不弹编辑浮层,所以不需要 vtCellEditor 插件)。当前启用 ${on} 行、VIP ${vip} 行`;
};

export default function VtCheckboxTable() {
  const containerRef = React.useRef<HTMLDivElement>(null);
  const [status, setStatus] = React.useState(describe);

  // 勾选写回后统计要跟着变。组件内部改的是行数据,冒泡上来的 change 事件是最省事的信号
  React.useEffect(() => {
    const el = containerRef.current;
    if (!el) return;
    const onChange = (): void => setStatus(describe());
    el.addEventListener('change', onChange);
    return () => el.removeEventListener('change', onChange);
  }, []);

  return (
    <div className="demo-wrapper">
      <h3 className="demo-title">React VtCheckbox 布尔勾选</h3>
      <div className="status-text">{status}</div>
      <div ref={containerRef} style={{ width: 820, height: 600 }} className="demo-container">
        <VirtTableReact
          columns={columns}
          options={{ list, itemKey: 'id', estimatedSize: 40, buffer: 4, border: true }}
        />
      </div>
    </div>
  );
}

说明 ​

「直接可点」类组件:交互与写回都发生在常态里,点一下就改值,不提供 renderEditor,也不需要 vtCellEditor 插件。给了 renderEditor 的话,装了编辑插件的人点勾选框会先弹出一个盖住勾选框的浮层,得点第二下才切换 —— 对一个开关型控件是纯粹的多余。

值不是 true / false 时配 trueValue / falseValue(1/0、'Y'/'N' 都常见)。

用字符串枚举时必须显式配 trueValue

不配就退回 JS 真值判断,'N'、'0' 这种非空字符串会被判成真。配了 trueValue 就只认它(严格相等)。

代价是这一列不参与「编辑态」语义(Esc 撤销、openCellEditor() 打开)—— 布尔列本来也没有可撤销的中间状态。皮肤直接用核心的 .vt-cell-bool + .vt-checkbox,与只读版 cellType: 'checkbox' 同源,视觉必然一致。

区别只在外观、值语义完全相同的还有 VtSwitch。

相关 API ​

字段作用
trueValue / falseValue写回的值,默认 true / false
col.align布尔列一般配 center

全量选项表见 单元格组件;公共选项 (placeholder / disabled / clearable / onChange)、asCell()、三类交互模型见 同页上方;列的通用字段见 列配置。

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