我需要对 2 列进行排序。
- 编号(1-200)
- 职称(AZ)
我怎么能用 onClick 做到这一点?
现在我正在排序,但是我无法以任何方式控制它,粗略地说,我在不按下按钮的情况下调用该函数,并且该列已经排序。
我将不胜感激任何帮助。
// Home.js
import React from "react";
import "./Home.css";
import { Link } from "react-router-dom";
export default class Home extends React.Component {
// Constructor
constructor(props) {
super(props);
this.state = {
sortItemsTitle: [],
sortItemsID: [],
items: [],
};
}
componentDidMount = () => {
this.apiFetch();
};
//Fetch data from API
apiFetch = () => {
return fetch("https://jsonplaceholder.typicode.com/todos")
.then((res) => res.json())
.then((json) => {
this.setState({
items: json,
});
});
};
// Sort Title (A-Z)
setSortedItemsTitle = () => {
// const sorted = items.sort((a, b) => a.title.localeCompare(b.title));
const { items } = this.state;
const sortedTitle = items.sort((a,b) => {
if (a.title < b.title) {
return -1;
}
if (a.title > b.title) {
return 1;
}
return 0;
})
console.log(sortedTitle);
};
// Sort ID (1-200)
setSortedItemsID = () => {
const { items } = this.state;
const sortedID = items.sort((a, b) => {
if (a.id < b.id) {
return items.direction === 'ascending' ? -1 : 1;
}
if (a.id > b.id) {
return items.direction === 'ascending' ? 1 : -1;
}
return 0;
})
console.log(sortedID);
};
render() {
const { items } = this.state;
return (
<div>
<h1>Home Page</h1>
<table>
<thead>
<tr>
<th>View Normal</th>
<th>Group By UserID</th>
</tr>
</thead>
<thead>
<tr>
<th>
ID
<button type="button" onClick={() => this.setSortedItemsID()}>⬇️</button>
</th>
<th>
User ID
</th>
<th>
Title
<button type="button" onClick={() => this.setSortedItemsTitle()}>⬇️</button>
</th>
<th>
Action
</th>
</tr>
</thead>
<tbody>
{items.map((item) => (
<tr key={item.id + item.title}>
<td>{item.id}</td>
<td>{item.userId}</td>
<td>{item.title}</td>
<td>
<Link target="self" to={`/details/${item.id}`}>
View Details
</Link>
</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
}
