reactjs - 在 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>
这是我的代码的功能。
解决方案
您可以添加一个状态变量来指示是升序还是降序进行排序,并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
在连续单击按名称排序按钮时切换或更新它。
推荐阅读
- android - 从活动中更改变量的片段值
- spring-boot - Spring boot 2.1 加载外部属性时,类路径中的应用程序属性被忽略
- ionic-framework - 装饰器不支持函数调用,但在 Ionic2 中使用 SwipeCardsModules 时在“NgModule”中调用了“makeDecorator”
- python - 从列表中取出最小的项目(字符串)
- spring-boot - 是否可以在 Spring Boot 中为嵌入式 tomcat 服务器打开会话复制?
- python - 从广播列表中删除元素
- liquibase - Liquibase diff 是否为您提供两个数据库之间的数据差异?
- parsing - 语法中是否存在跟随冲突?
- mysql - 如何在 Socket IO 事件循环中处理 Knex 更新查询
- blueprism - Blue Prism 使用什么版本的编译器?