如何使用ReactJS以两种方式对表中的列进行排序 [英] How to make columns in table sortable in both ways using ReactJS
问题描述
我正在ReactJS中构建一个简单的应用程序,它通过调用某个API来使用JSON数组。然后我在表中填充数组的结果。我现在想让表的列可以排序。我理想的是要进行升序和降序排序。一旦我按升序排序时点击标题,它应该按降序排序,反之亦然。这是我的代码。
I am building a simple app in ReactJS that works with a JSON array by calling a certain API. I am then populating the results of the array in a table. I now wanted to make the columns of the table sortable. What I ideally want is to have both ascending and descending sorting. Once I click on the header when it is sorted ascending, it should sort descending and vice-versa. Here is my code.
class ParentComponent extends Component {
constructor(props) {
super(props);
this.state = { data: [] };
}
componentDidMount() {
fetch("http://hostname:xxxx/yyyy/zzzz")
.then(function(response) {
return response.json();
})
.then(items => this.setState({ data: items }));
}
render() {
var newdata = this.state.data;
return (
<table className="m-table">
<thead>
<tr>
<th>AccountName</th>
<th>ContractValue</th>
</tr>
</thead>
<tbody>
{newdata.map(function(account, index) {
return (
<tr key={index} data-item={account}>
<td data-title="Account">{account.accountname}</td>
<td data-title="Value">{account.negotiatedcontractvalue}</td>
</tr>
);
})}
</tbody>
</table>
);
}
}
export default ParentComponent;
推荐答案
您可以添加排序
您所在州的财产列
和方向
属性:
You can add a sort
property to your state with column
and direction
properties:
state = {
data: [],
sort: {
column: null,
direction: desc,
},
};
当然你也应该有一个像这样的排序处理程序:
Of course you should also have a sort handler like so:
onSort = (column) => (e) => {
const direction = this.state.sort.column ? (this.state.sort.direction === 'asc' ? 'desc' : 'asc') : 'desc';
const sortedData = this.state.data.sort((a, b) => {
if (column === 'accountName') {
const nameA = a.accountName.toUpperCase(); // ignore upper and lowercase
const nameB = b.accountName.toUpperCase(); // ignore upper and lowercase
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}
// names must be equal
return 0;
} else {
return a.contractValue - b.contractValue;
}
});
if (direction === 'desc') {
sortedData.reverse();
}
this.setState({
data: sortedData,
sort: {
column,
direction,
}
});
};
我从 MDN 。
这是一支示例笔: https://codepen.io/anon/pen/xrGJKv
这篇关于如何使用ReactJS以两种方式对表中的列进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!