React使用Material-UI Table如何实现宝可梦列表按名称排序
问题排查
- 已编写的排序工具函数未被调用,渲染列表时直接遍历了原始
pokemons数组,排序逻辑未生效 - 未声明状态管理当前排序方向、排序字段两个核心排序参数
- 表头的名称列未绑定点击事件,无法触发排序交互
修复后的完整代码
import React, { useState } from "react"; import { Table, TableBody, TableContainer, TableHead, TableRow, TableCell, TableSortLabel } from "@material-ui/core"; import { pokemons } from "./data"; import "./styles.css"; const App = () => { // 新增排序状态管理 const [order, setOrder] = useState('asc'); const [orderBy, setOrderBy] = useState('name'); function descendingComparator(a, b, orderBy) { if (b[orderBy] < a[orderBy]) { return -1; } if (b[orderBy] > a[orderBy]) { return 1; } return 0; } function getComparator(order, orderBy) { return order === "desc" ? (a, b) => descendingComparator(a, b, orderBy) : (a, b) => -descendingComparator(a, b, orderBy); } function stableSort(array, comparator) { const stabilizedThis = array.map((el, index) => [el, index]); stabilizedThis.sort((a, b) => { const order = comparator(a[0], b[0]); if (order !== 0) { return order; } return a[1] - b[1]; }); return stabilizedThis.map((el) => el[0]); } // 新增表头点击触发排序的处理函数 const handleSortChange = () => { setOrder(prev => prev === 'asc' ? 'desc' : 'asc'); }; return ( <TableContainer> <Table sx={{ maxWidth: 650 }}> <TableHead> <TableRow> <TableCell>Pokémon</TableCell> {/* 表头名称列新增排序交互 */} <TableCell align="right" sortDirection={order}> <TableSortLabel active={true} direction={order} onClick={handleSortChange} > Name </TableSortLabel> </TableCell> </TableRow> </TableHead> <TableBody> {/* 渲染前先调用排序函数处理数组 */} {stableSort(pokemons, getComparator(order, orderBy)).map((pokemon) => ( <TableRow key={pokemon.name} sx={{ "&:last-child td, &:last-child th": { border: 0 } }} > <TableCell component="th" scope="row" thumbnailImage> <div className="thumb"> <img src={pokemon.thumbnailImage} alt="" /> </div> </TableCell> <TableCell align="left" component="th" scope="row" description> {pokemon.name} </TableCell> </TableRow> ))} </TableBody> </Table> </TableContainer> ); }; export default App;
内容的提问来源于stack exchange,提问作者Tainara
相关产品推荐
相关产品推荐

