【发布时间】:2020-01-06 03:58:04
【问题描述】:
我正在使用这张桌子。到目前为止,当单击“日期”列时,它会按升序对表格进行排序。我希望能够再次单击它并让它返回到降序。关于如何做的任何想法?
我知道在 => 之后在 sortBy 中切换我的 a 和 b 会适得其反。
class Orders extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [
{orders: 'Vanilla', date: '03/15/1990'},
{orders: 'Chocolate', date: '03/15/1989'},
],
};
this.sortBy.bind(this);
}
renderTableData() {
return this.state.data.map((data, index) => {
const{orders, date} = data
return (
<tr key={index}>
<td>{orders}</td>
<td>{date}</td>
</tr>
)
})
}
sortBy(sortedKey) {
const data = this.state.data;
data.sort((a,b) => a[sortedKey].localeCompare(b[sortedKey]))
this.setState({data})
}
render() {
let newData = this.state.data;
return (
<table id="orders">
<tr className="header">
<th>Order</th>
<th onClick={() => this.sortBy('date')}>Date</th>
</tr>
<tbody>
{this.renderTableData()}
</tbody>
</table>
);
}
}
export default Orders;
【问题讨论】:
标签: javascript reactjs