javascript - 在react中多次使用排序函数

标签 javascript reactjs sorting

现在我有一个表,其中包含来自 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/

相关文章:

C++ STL : Custom sorting one vector based on contents of another

javascript - 如何在按钮上单击 JqGrid 文本框值

reactjs - react : If you set state in a request animation frame will react schedule rendering on the animation frame?

reactjs - 如何正确删除组件上的填充

reactjs - 如何使用 Nav.Link 和 React Router 在导航栏中设置事件链接?

sorting - 格式列表 : sort properties by name

javascript - 使用Express JS进行API外部CALL(避免cors问题)

javascript - 更改字段属性

javascript - 如何向正在运行的 setInterval 添加暂停/播放功能?

c++ - Qt:QTableWidget 将整数添加到表中