【发布时间】:2021-08-29 19:37:45
【问题描述】:
我想在反应中对每一列进行排序。我可以做到,但是强制代码,例如,如果我有这个数组并将其显示在一个 html 表中,我希望当我单击 id 时它按升序排序,当我单击名称时它按升序排序,然后再次单击它按降序排序,我想要名称和年龄相同。同时我想要一个箭头,如果该列在升序中,则向上查找,否则向下查找。
const USERS = [
{ id: 1, name: "Andy", age: 32 },
{ id: 2, name: "Bob", age: 30 },
{ id: 3, name: "Tom Hulk", age: 40 },
{ id: 4, name: "Tom Hank", age: 50 },
{ id: 5, name: "Audra", age: 30 },
{ id: 6, name: "Anna", age: 68 },
{ id: 7, name: "Tom", age: 34 },
{ id: 8, name: "Tom Riddle", age: 28 },
{ id: 9, name: "Bolo", age: 23 },
];
我可以做到的方式是这样的,但它很难看,也不实用。而且,当我更改箭头的排序状态时,它会更新所有箭头而不是我单击的列的箭头
const sortBy = (k) => {
if (k === "id") {
if (sort) {
const res = USERS.sort((a, b) => (a.id > b.id ? 1 : -1));
setDataFilter(res);
setSort(!sort);
console.log(res);
} else {
const res = USERS.sort((a, b) => (a.id < b.id ? 1 : -1));
setDataFilter(res);
setSort(!sort);
console.log(res);
}
} else if (k === "age") {
if (sort) {
const res = USERS.sort((a, b) => (a.age > b.age ? 1 : -1));
setDataFilter(res);
setSort(!sort);
console.log(res);
} else {
const res = USERS.sort((a, b) => (a.age < b.agek ? 1 : -1));
setDataFilter(res);
setSort(!sort);
console.log(res);
}
} else if (k === "name") {
if (sort) {
const res = USERS.sort((a, b) => a.name.localeCompare(b.name));
setDataFilter(res);
setSort(!sort);
console.log(res);
} else {
const res = USERS.sort((a, b) => b.name.localeCompare(a.name));
setDataFilter(res);
setSort(!sort);
console.log(res);
}
} else {
console.log("hmm");
}
};
【问题讨论】:
-
只需编写一个函数,该函数接受您要排序的属性和排序类型的参数。
标签: javascript html reactjs sorting html-table