当我的表头数据放在 .map() 方法中时,我正在尝试对表进行排序(升序/降序)(请参阅本文中代码框链接的第 73 行)。
我可以让手形表情符号更改 onClick,但不会进行排序。我认为这可能与将对象传递给 map 方法有关,而不是在我基于此功能的代码框中找到的单个字符串或数值。这是我建模的原始沙箱: https ://codesandbox.io/embed/table-sorting-example-ur2z9?fontsize=14&hidenavigation=1&theme=dark
...这是我需要排序的数据结构的代码框: https ://codesandbox.io/s/table-sorting-example-forked-dofhj?file=/src/App.js
为了使每列可排序,我可以更改什么?任何帮助/建议将不胜感激。
应用程序.js
import React from "react";
import "./styles.css";
import {
Button,
Table,
Thead,
Tbody,
Flex,
Tooltip,
Tr,
Th,
Td
} from "@chakra-ui/react";
//Table Headers
const TABLE_HEADERS = [
{ name: "ID Number" },
{ name: "User Type" },
{ name: "User Category" },
{ name: "User Interest" }
];
const useSortableData = (items, config = null) => {
const [sortConfig, setSortConfig] = React.useState(config);
const sortedItems = React.useMemo(() => {
let sortableItems = [...items];
if (sortConfig !== null) {
sortableItems.sort((a, b) => {
if (a[sortConfig.key] < b[sortConfig.key]) {
return sortConfig.direction === "ascending" ? -1 : 1;
}
if (a[sortConfig.key] > b[sortConfig.key]) {
return sortConfig.direction === "ascending" ? 1 : -1;
}
return 0;
});
}
return sortableItems;
}, [items, sortConfig]);
const requestSort = (key) => {
let direction = "ascending";
if (
sortConfig &&
sortConfig.key === key &&
sortConfig.direction === "ascending"
) {
direction = "descending";
}
setSortConfig({ key, direction });
};
return { items: sortedItems, requestSort, sortConfig };
};
const ProductTable = (props) => {
const { items, requestSort, sortConfig } = useSortableData(
props.myUserErrorTypes
);
const getClassNamesFor = (name) => {
if (!sortConfig) {
return;
}
return sortConfig.key === name ? sortConfig.direction : undefined;
};
return (
<Table>
<caption>User Error Types</caption>
<Thead>
<Tr>
{TABLE_HEADERS.map(({ name, description, isNumeric }) => (
<Th key={name} isNumeric={isNumeric}>
<Button
type="button"
onClick={() => requestSort(name)}
className={getClassNamesFor(name)}
>
<Tooltip label={description} aria-label={description}>
{name}
</Tooltip>
</Button>
</Th>
))}
</Tr>
</Thead>
<Tbody>
{items.map((error) => {
const { userNumber, userType, errorId, errorCategory } = error;
return (
<React.Fragment key={errorId}>
<Tr id={errorId} key={errorId}>
<Td>{userNumber}</Td>
<Td>{userType}</Td>
<Td>{errorId}</Td>
<Td>{errorCategory}</Td>
<Td textAlign="center">
<Flex justify="justifyContent"></Flex>
</Td>
</Tr>
</React.Fragment>
);
})}
</Tbody>
</Table>
);
};
export default function App() {
return (
<div className="App">
<ProductTable
myUserErrorTypes={[
{
userNumber: 1234567890,
userType: "SuperUser",
errorId: 406,
errorCategory: "In-Progress"
},
{
userNumber: 4859687937,
userType: "NewUser",
errorId: 333,
errorCategory: "Complete"
}
]}
/>
</div>
);
}