简体   繁体   English

如何对 react-bootstrap Table 组件进行排序

[英]How to sort react-bootstrap Table component

I'm new to React and am using the Table component from react-bootstrap .我是 React 新手,正在使用react-bootstrap中的 Table 组件。

I want to sort my table in ascending order of the 'Days Till Expiry' column.我想按“到期天数”列的升序对表格进行排序。 我的反应应用

But the Table component doesn't have a sorting property, does anyone know how I could do this?但是 Table 组件没有排序属性,有人知道我该怎么做吗?

我建议使用react-bootstrap-table然后使用这些示例

Personally I did it by adding an onClick event on the header and having said event trigger a sorting function I'd programmed.就我个人而言,我通过在标题上添加一个 onClick 事件并让该事件触发我编写的排序功能来做到这一点。 To ensure the change shows up, I added a state I could just update to render the table whenever I made a change.为了确保显示更改,我添加了一个状态,我可以在进行更改时更新以呈现表格。 Here is what it looks like:这是它的样子:

    <th className ="text-center" onClick= {()=>sortFunction('headerName')}>HeaderName</th>

and here is an abridged version of the function itself:这是该函数本身的精简版:

    function sortFunction(col){
    switch (col){
    case "headerName":
    dataArray.sort((a, b)=>{
      if(a.attribute>b.attribute){
        return 1:-1;
      }
      if(a.attribute<b.attribute){
        return -1;
      }
      return 0;
    });
    break;
    default:
    //you might want to do something as default, I don't
    break;
    setSort(sort+1);

just keep in mind I declared the state with:请记住,我用以下方式声明了状态:

    const [sort, setSort] = useState(0);

When comparing two strings, make sure to use localeCompare and not ><.比较两个字符串时,请确保使用 localeCompare 而不是 ><。 The beauty of using a custom sorting function is you get to choose how things are compared, meaning you can sort however you would like.使用自定义排序功能的好处在于您可以选择比较事物的方式,这意味着您可以随意排序。 I also added another variable later to handle the order and swapping the order when sorting the table.稍后我还添加了另一个变量来处理订单并在对表格进行排序时交换订单。

In your case I would do something like:在你的情况下,我会做类似的事情:

    dataArray.sort((a, b)=>{
      if(new Date(a.daysTillExpiry).getTime()>new Date(b.daysTillExpiry).getTime()){
        return 1;
      }
      if(new Date(a.daysTillExpiry).getTime()<new Date(b.daysTillExpiry).getTime()){
        return -1;
      }
      return 0;
    });
    setSort(sort+1);

Keep in mind I didn't try it specifically for your order so maybe you'll have to reverse the return 1 and return -1 to get the proper ordering.请记住,我没有专门为您的订单尝试它,所以也许您必须反转 return 1 并 return -1 以获得正确的排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM