【发布时间】:2021-09-29 05:22:24
【问题描述】:
所以我有它,以便默认情况下对 Name 列进行排序 (ASC) - 我只需要计算 onclick 以便在单击时更改此排序顺序。
function descendingComparator(a,b, orderBy) {
console.log('a',a)
console.log('b',b)
console.log('orderBy',orderBy)
if(b[orderBy] < a[orderBy]){
console.log('-1')
return -1;
}
if(b[orderBy] > a[orderBy]){
console.log('1')
return 1;
}
console.log('0')
return 0;
}
function getComparator(order, orderBy){
return order === "desc"
? (a,b) => descendingComparator(a,b, orderBy)
: (a,b) => -descendingComparator(a,b, orderBy)
}
const sortedRowInformation = (rowArray, comparator) => {
const stabilizedRowArray = rowArray.map((el, index) => [el, index])
stabilizedRowArray.sort((a,b) =>{
const order = comparator(a[0], b[0])
if(order !==0) return order;
return a[1] - b[1];
})
return stabilizedRowArray.map((el) => el[0])
}
const [page, setPage] = useState(0)
const [rowsPerPage, setRowsPerPage] = useState(5)
const [pageIndex, setPageIndex] = useState(0)
const [order, setOrder] = useState()
const [orderBy, setorderBy] = useState()
const [orderDirection, setorderDirection] = useState("asc")
const [valueToOrderBy, setvalueToOrderBy] = useState("Name")
还有我的桌子:
<TableCell align = "left" key = "system">
<TableSortLabel
active={valueToOrderBy === "Name"}
direction={valueToOrderBy === "Name" ? orderDirection: 'asc'}
onClick={createSortHandle("Name")}
>
NAME
</TableSortLabel>
</TableCell>
<TableBody>
{
sortedRowInformation(listItemFood, getComparator(orderDirection, valueToOrderBy))
.map((item, index1) => (
<TableRow hover key={item.id} id={item.id}>
<TableCell>{item.Category}</TableCell>
<TableCell><a href="#updateItem" onClick={() => editItem(item)}>{item.Name}</a></TableCell>
<TableCell>{item.Weight}</TableCell>
<TableCell>
<IconButton size="small" aria-label="edit" onClick={() => editItem(item)}><a href="#updateItem"><EditOutlinedIcon /></a></IconButton><IconButton size="small" aria-label="delete" onClick={() => deleteItem(item.id)}><DeleteIcon /></IconButton>
</TableCell>
</TableRow>
))}
</TableBody>
我需要附加到 onClick={createSortHandle("Name")} 的函数是什么,以便在点击时改变方向?
【问题讨论】:
-
能否提供完整的代码,这样解决问题就容易多了?
-
也添加到 TableBody 中 - 有帮助吗?
-
希望您可以提供完整的代码或代码沙箱,以便重新创建您面临的问题。用很少的代码-sn-ps 不能真正得到一个完整的想法。我只是提出一个答案,请检查您是否可以修改您的实现。
标签: reactjs material-ui