首页 > 解决方案 > 在 React 中切换排序功能

问题描述

我创建了一个显示价格的表格和一个对它们进行排序的函数,但我不知道如何在升序和降序之间切换。

...//my states
      this.compareBy.bind(this);
      this.sortBy.bind(this);
  };

  compareBy(key) {
    return function (a, b) {
      if (a[key] < b[key]) return -1;
      if (a[key] > b[key]) return 1;
      return 0;
    };
  }


  sortBy(key) {
    let arrayCopy = [...this.state.data];
    arrayCopy.sort(this.compareBy(key));
    this.setState({data: arrayCopy});
  }

 <th  onClick={() => this.sortBy('name')}>Name</th>

这是我的代码的功能。

标签: reactjsfunctionsortingtoggle

解决方案


您可以添加一个状态变量来指示是升序还是降序进行排序,并compareBy相应地更新函数。

例如,如果您命名状态变量sortAscending( boolean),您可以更新compareBy为如下所示:

compareBy(key) {
  const { sortAscending } = this.state;
  return function (a, b) {
    if (a[key] < b[key]) return sortAscending ? -1 : 1;
    if (a[key] > b[key]) return sortAscending ? 1 : -1;
    return 0;
  };
}

然后在某处添加一个按钮以sortAscending在连续单击按名称排序按钮时切换或更新它。


推荐阅读