這幾天我一直在嘗試解決這個問題,但一無所獲。我正在嘗試使用 adazzle 的 React-data-grid 庫使我的表列可過濾和可排序。這是我的程式碼。我不知道下一步該做什麼。如果有人熟悉這個請幫助我。
我已經嘗試了幾乎所有的方法。我想使用 adazzle 的 React-data-grid 庫使我的表格列可過濾和可排序。
import React, { useState, useEffect } from "react"; import ReactDataGrid from "react-data-grid"; //import { Toolbar, Filters } from "react-data-grid-addons"; function Data() { const [columns, setColumns] = useState([]); const [rows, setRows] = useState([]); useEffect(() => { const defaultComponentProperties = { resizable: true, filterable: true, sortable: true, }; // Fetch grid configuration fetch('../local-json/gridConfig.json') .then(response => response.json()) .then(myConfig => { myConfig = myConfig.map(c => ({...c, ...defaultComponentProperties})) setColumns(myConfig) }) .catch(error => { console.error('Error fetching grid configuration:', error); }) // .catch((error) => { // console.error("Error fetching grid configuration:", error); // }); // Fetch grid data fetch('../local-json/gridData.json') .then(response => response.json()) .then(myData => { setRows(myData); }) .catch(error => { console.error('Error fetching grid data:', error); }); }, []) // .catch((error) => { // console.error("Error fetching grid data:", error); // }); return ( <div className="grid-container"> <ReactDataGrid columns={columns} rowGetter={i => rows[i]} rowsCount={rows.length} minHeight={300} onColumnResize={(idx, width) => console.log(`Column ${idx} has been resized to ${width}`) } enableCellSelect /> </div> ); } export default Data;
P粉9330033502023-09-15 00:06:15
// handle the filtering const handleFilterChange = (filter) => { const newFilters = { ...filters }; if (filter.filterTerm) { newFilters[filter.column.key] = filter; } else { delete newFilters[filter.column.key]; } setFilters(newFilters); }; const getValidFilterValues = (columnId) => { let values = rows.map((r) => r[columnId]); return values.filter((item, i, a) => { return i === a.indexOf(item); }); }; // clearing filters const onClearFilters = () => { setFilters({}); }; // handle sorting const handleSort = (sortColumn, sortDirection) => { const sortedRows = [...rows]; sortedRows.sort((a, b) => { const valueA = a[sortColumn]; const valueB = b[sortColumn]; if (sortDirection === "ASC") { return valueA < valueB ? -1 : valueA > valueB ? 1 : 0; } else if (sortDirection === "DESC") { return valueA > valueB ? -1 : valueA < valueB ? 1 : 0; } return 0; }); setRows(sortedRows); };