React 字段配置(列显隐 / 列序)
字段配置面板 = 勾选控制列显隐 + 拖手柄调整列序。列支持 hidden(默认隐藏)与 hideable: false(禁止在面板切换)。装载 vtFieldConfig() 后用 ref 上的 toggleFieldConfig(anchor) 打开面板,或用 setColumnVisible(key, visible) / moveColumn() 编程控制。
装了 vtToolbar 时它会把自己挂成工具栏上的「字段配置」那颗按钮 —— 工具栏一颗都不自带,所以这个插件(或 ...vtToolbarPanels() 那个预设)必须写出来。选项见 vanilla 版。
示例
微应用尚未挂载。
源码
点击查看源码
tsx
import React from 'react';
import {
VirtTableReact,
type ReactTableColumn,
type VirtTableRef,
vtFieldConfig,
} from '@virt-table/react';
import { faker } from '@faker-js/faker';
interface Row extends Record<string, unknown> {
id: number;
name: string;
age: number;
city: string;
job: string;
email: string;
}
const columns: ReactTableColumn<Row>[] = [
{ key: 'id', title: 'ID', width: 80, hideable: false },
{ key: 'name', title: '姓名', width: 160 },
{ key: 'age', title: '年龄', width: 120 },
{ key: 'city', title: '城市', width: 160 },
{ key: 'job', title: '职位', width: 200 },
{ key: 'email', title: '邮箱', width: 240, hidden: true },
];
const list: Row[] = Array.from({ length: 500 }, (_, i) => ({
id: i + 1,
name: faker.person.fullName(),
age: faker.number.int({ min: 18, max: 60 }),
city: faker.location.city(),
job: faker.person.jobTitle(),
email: faker.internet.email(),
}));
export default function ColumnVisibilityTable() {
const tableRef = React.useRef<VirtTableRef>(null);
const plugins = React.useMemo(() => [vtFieldConfig()], []);
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"
// 面板要贴着触发按钮定位,所以把按钮本身作为 anchor 传进去
onClick={(e) => tableRef.current?.toggleFieldConfig(e.currentTarget)}
>
字段配置
</button>
<button
type="button"
className="virt-table-btn"
onClick={() => tableRef.current?.setColumnVisible('job', false)}
>
隐藏「职位」
</button>
<button
type="button"
className="virt-table-btn"
onClick={() => tableRef.current?.setColumnVisible('email', true)}
>
显示「邮箱」
</button>
<span className="demo-note">ID 列不可隐藏;邮箱列默认隐藏</span>
</div>
<div style={{ width: 760, height: 460 }} className="demo-container">
<VirtTableReact
ref={tableRef}
columns={columns}
options={{ list, itemKey: 'id', estimatedSize: 40, buffer: 6, border: true, plugins }}
/>
</div>
</div>
);
}说明
相关 API
| 字段 / 方法 | 作用 | 详见 |
|---|---|---|
col.hidden / col.hideable | 默认隐藏 / 允不允许用户切换 | 列配置 · 列显隐 |
setColumnVisible(colKey, visible) | 编程式显隐 | 列配置 · 列显隐 |
getVisibleColumns / getLeafColumns / getAllColumns | 三种读列口径 | 实例方法 |
toggleFieldConfig(anchor?) | 打开 / 关闭面板 | 插件机制 |
moveColumn(fromKey, toKey, after) | 编程式换序(面板里拖手柄落的就是它) | 实例方法 |
getState() / setState() | 把列显隐存下来 | 状态持久化 |
上面的字段在 React 端原样透传(实例方法通过组件
ref调用)。封装层特有的部分 —— 组件 Props、渲染函数返回 JSX、ref转发了哪些方法 —— 见 React API。