昨天文章補齊加上瘋狂抱怨大會
果然大公司鬼故事不是一般多
今天繼續PrimeReact DataTable
動態顯示欄位
先來設定interface
export interface Product {
id: string;
code: string;
name: string;
description: string;
image: string;
price: number;
category: string;
quantity: number;
inventoryStatus: string;
rating: number;
}
export interface ColumnMeta {
field: string;
header: string;
}
再來引用元件跟資料還有interface,
因為動態選擇是使用multiselect,所以多引用這項
import { DataTable } from 'primereact/datatable';
import { Column } from 'primereact/column';
import { MultiSelect, MultiSelectChangeEvent } from 'primereact/multiselect';
import { ProductService } from '../service/table';
import { Product, ColumnMeta } from '../interfaces/table';
const columns: ColumnMeta[] = [
{ field: 'name', header: 'Name' },
{ field: 'category', header: 'Category' },
{ field: 'quantity', header: 'Quantity' }
];
再來套元件(完整程式碼)
import React, { useEffect, useState } from 'react';
import { DataTable } from 'primereact/datatable';
import { Column } from 'primereact/column';
import { MultiSelect, MultiSelectChangeEvent } from 'primereact/multiselect';
import { ProductService } from '../service/table';
import { Product, ColumnMeta } from '../interfaces/table';
const columns: ColumnMeta[] = [
{ field: 'name', header: 'Name' },
{ field: 'category', header: 'Category' },
{ field: 'quantity', header: 'Quantity' }
];
const Tables7Compnent: React.FC = () => {
let service = new ProductService();
const [products, setProducts] = useState<Product[]>([]);
const [visibleColumns, setVisibleColumns] = useState<ColumnMeta[]>(columns);
useEffect(() => {
service.getProductsMini().then((data) => setProducts(data));
}, []);
const onColumnToggle = (event: MultiSelectChangeEvent) => {
let selectedColumns = event.value;
let orderedSelectedColumns = columns.filter((col) => selectedColumns.some((sCol:ColumnMeta) => sCol.field === col.field));
setVisibleColumns(orderedSelectedColumns);
};
const header = <MultiSelect value={visibleColumns} options={columns} optionLabel="header" onChange={onColumnToggle} display="chip" />;
return (
<div>
<DataTable value={products} header={header} >
<Column field="code" header="Code" />
{visibleColumns.map((col) => (
<Column key={col.field} field={col.field} header={col.header} />
))}
</DataTable>
</div>
);
}
export default Tables7Compnent;
主要就是利用useState 加map 去決定怎麼顯示,
要說primereact 關係性其實沒那麼高,
但這是這算是頗常用的功能,
那麼,今天就到這啦
明天見!