今天繼續PrimeReact DataTable
今天來說說我也覺得很棒的api
reorderableRows 跟 reorderableColumns
這是具有拖曳能功能的api
用過beautiful dnd刻元件,
覺得只要加一行就有這功能真是太棒了
那麼開始吧
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;
}
再來引用套(完整程式碼)
import React, { useEffect, useState } from 'react';
import { DataTable } from 'primereact/datatable';
import { Column } from 'primereact/column';
import { ProductService } from '../service/table';
import { Product, ColumnMeta } from '../interfaces/table';
const Tables8Compnent: React.FC = () => {
let service = new ProductService();
const [tabledata, setTabledata] = useState<Product[]>();
const columns: ColumnMeta[] = [
{ field: 'code', header: 'Code' },
{ field: 'name', header: 'Name' },
{ field: 'category', header: 'Category' },
{ field: 'quantity', header: 'Quantity' }
];
useEffect(() => {
service.getProductsMini().then(data => setTabledata(data));
}, []);
const dynamicColumns = columns.map((col) => {
return <Column key={col.field} columnKey={col.field} field={col.field} header={col.header} />;
});
return (
<div>
<DataTable
tableStyle={{ 'userSelect': 'none' }}
value={tabledata}
reorderableRows
reorderableColumns
onRowReorder={(e) => setTabledata(e.value)}>
<Column rowReorder></Column>
{dynamicColumns}
</DataTable>
</div>
);
}
export default Tables8Compnent;
※建議增加 user-select: none; 滑鼠拖曳起來會感覺比較順暢
reorderableColumns
添加後,拖曳欄位的header的部分可以移動
reorderableRows
開啟要記得增加拖曳手柄的設定
<Column rowReorder></Column>
這個
那麼今天就到這了,明天見