react排序(sort)

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>
    );
  }
}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值