现在我有一个表,其中包含来自 github api 的一些数据。 在表中,您可以单击“星星”标题,它将列表从 0 到 * 排序。 我的函数适用于一列。但是我怎样才能在不同的列上反复使用这个函数呢?
我的表格标题:
<th>Name</th>
<th onClick={this.sortList}>Stars</th>
{* This should update value forks_count *}
<th onClick={this.sortList}>Forks</th>
我的功能:
我所做的是获取数组并根据 stargazers_count 对它进行排序。这是可行的,但是当我想对我的 fork 计数进行排序时..stargazers_count 应该是 forks_count。这可能吗?
sortList = () => {
const items = this.props.repos;
items.sort(function (a, b) {
//stargazers_count should be forks_count when I click on forks heading
return a.stargazers_count - b.stargazers_count;
});
this.setState({
repos: items
})
};
最佳答案
有闭包:
<th>Name</th>
<th onClick={this.sortListBy("stargazers_count")}>Stars</th>
{* This should update value forks_count *}
<th onClick={this.sortListBy("forks_count")}>Forks</th>
sortListBy = (prop) => () => {
const items = this.props.repos;
items.sort(function (a, b) {
return a[prop] - b[prop];
});
this.setState({
repos: items
})
};
关于javascript - 在react中多次使用排序函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46971390/