Appearance
React 列显隐 / 列设置
列支持 hidden(默认隐藏)与 hideable: false(禁止在面板切换)。装载 vtColumnPanel() 后用 ref 上的 toggleColumnPanel() 打开列设置面板,或用 setColumnVisible(key, visible) 编程控制。
使用的 API
tsx
import { VirtTableReact, vtColumnPanel } from '@virt-table/react';
const columns: ReactTableColumn<Row>[] = [
{ key: 'id', title: 'ID', width: 80, hideable: false }, // 不允许隐藏
{ key: 'email', title: '邮箱', width: 240, hidden: true }, // 默认隐藏
];
const plugins = React.useMemo(() => [vtColumnPanel()], []);
// 实例方法(ref 上调用);面板要贴着触发按钮定位,把按钮作为 anchor 传进去
onClick={(e) => tableRef.current?.toggleColumnPanel(e.currentTarget)}
tableRef.current?.setColumnVisible('job', false);
tableRef.current?.getVisibleColumns();示例
微应用尚未挂载。
源码
点击查看源码
tsx
import React from 'react';
import {
VirtTableReact,
type ReactTableColumn,
type VirtTableRef,
vtColumnPanel,
} 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(() => [vtColumnPanel()], []);
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?.toggleColumnPanel(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>
);
}