import React, { Component } from "react";
export default class App extends Component {
state = {
tableData: [
{
name: "John ll",
score: 62.7,
},
{
name: "John hh",
score: 76,
},
{
name: "John gg",
score: 96.5,
},
{
name: "John aa",
score: 64,
},
{
name: "John bb",
score: 131,
},
{
name: "John dd",
score: 58,
},
{
name: "John cc",
score: 50.8,
},
],
columns: [
{
title: "Name",
dataIndex: "name",
key: "name",
},
{
title: "Score",
dataIndex: "score",
key: "score",
},
],
// 排序类型
sortTypes: {
//升序
up: {
class: "sort-up",
fn: (a, b) => a.score - b.score,
},
//降序
down: {
class: "sort-down",
fn: (a, b) => b.score - a.score,
},
//默认不排序
default: {
class: "sort",
fn: (a, b) => a,
},
},
// 当前排序
currentSort: "default",
};
//实现排序的方法
onSortChange = () => {
const { currentSort } = this.state;
let nextSort;
//排序方式的切换
if (currentSort === "down") nextSort = "up";
else if (currentSort === "up") nextSort = "default";
else if (currentSort === "default") nextSort = "down";
//修改当前排序方式
this.setState({
currentSort: nextSort,
});
};
render() {
return (
<div>
<div className="text-center">
{/* 排序按钮 动态传值 */}
<button onClick={() => this.onSortChange()}>
{this.state.sortTypes[this.state.currentSort].class}
</button>
{/* 内容 */}
<table className="text-left">
{/* 标题 */}
<thead>
<tr>
<th>Name</th>
<th>Score</th>
</tr>
</thead>
{/* 内容 */}
<tbody>
{[...this.state.tableData]
.sort(this.state.sortTypes[this.state.currentSort].fn)
.map((p) => (
<tr>
<td>{p.name}</td>
<td>${p.score}b</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
);
}
}
react排序(sort)
最新推荐文章于 2024-03-29 18:20:52 发布