【问题标题】:How to sort the antd-table while keep one special line forever on the top of the table?如何对 antd-table 进行排序,同时将一条特殊行永远保留在 table 顶部?
【发布时间】:2020-11-27 18:43:59
【问题描述】:

我正在使用 react 和 ant design 3.26 构建我的网站,并使用 antd_table 显示一些数据。现在我需要对表格进行排序,同时将一个特殊行永久保留在表格顶部,并且不受分拣机(既不下降也不上升)。我有一些简单的方法来制作这个效果吗?

我不想用onChange()做一些复杂的功能来管理数据源和状态,只想使用antd-table提供的默认sorter props。

这是一个简单的演示:

import React from "react";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import "./index.css";
import { Table} from "antd";

const data = [
  {
    key: '1',
    name: 'John Brown',
    age: 32,
    address: 'New York No. 1 Lake Park',
    shouldForeverTop: true,
  },
  {
    key: '2',
    name: 'Jim Green',
    age: 42,
    address: 'London No. 1 Lake Park',
    shouldForeverTop: false,
  },
  {
    key: '3',
    name: 'Joe Black',
    age: 32,
    address: 'Sidney No. 1 Lake Park',
    shouldForeverTop: false,
  },
  {
    key: '4',
    name: 'Jim Red',
    age: 32,
    address: 'London No. 2 Lake Park',
    shouldForeverTop: false,
  },
];

class App extends React.Component {
  render() {
    const columns = [
      {
        title: 'Name',
        dataIndex: 'name',
        sorter: (a, b) => a.name.length - b.name.length,
      },
      {
        title: 'Age',
        dataIndex: 'age',
        sorter: (a, b) => a.age - b.age,
      },
      {
        title: 'Address',
        dataIndex: 'address',
        sorter: (a, b) => a.address.length - b.address.length,
      },
    ];
    return (
        <Table columns={columns} dataSource={data}/>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("container"));

【问题讨论】:

    标签: html reactjs antd


    【解决方案1】:

    可以将第一行数据与a或b进行比较,如果是a.name === data[0].namereturn 0

     sorter: (a, b) => {
       if(a.name === data[0].name || b.name === data[0].name) return 0;
       return a.name.length - b.name.length
     },
    
    

    【讨论】:

    • 感激不尽。这个答案非常有用和优雅,让我知道sorter()如何对数组进行排序,再次感谢。
    【解决方案2】:

    关于 sorter() 的工作原理:a 和 b 是值,或者在您的情况下是要考虑的名称。一开始,a 将是列中的第一个名称,b 是第二个,然后它将在列中向下移动。好吧,排序器实际上返回真或假。因此,假设列中的第一个名字是 jim,第二个是 john。现在,当 a.name.length(即 3)- b.name.length(即 4)时,3-4 返回 false(因为它是 -1),因此名称不会互换,jim 将留在约翰。现在再往下移动,john 将变为 a,下一个名字,比如 tim,将变为 b,然后再次在这两者之间进行比较。如果 sorter 返回 true(在这种 john 和 tim 的情况下,它将返回 true),那么就会发生交换。希望很清楚。

    【讨论】:

      猜你喜欢
      • 2014-09-05
      • 2018-02-12
      • 1970-01-01
      • 1970-01-01
      • 2019-08-15
      • 2018-09-19
      • 1970-01-01
      • 1970-01-01
      • 2019-08-08
      相关资源
      最近更新 更多