如何在ReactJS中对HTML表格进行排序
问题描述:
我有array
的Objects
,我将数据添加到HTML Table
。现在我需要按版本对数据进行排序。我如何在React
中做类似的事情?如何在ReactJS中对HTML表格进行排序
render() {
return (
<div>
<div>
<Label> We got {this.state.count} elements in our database. </Label>
</div>
<div>
<Table hover striped bordered responsive size="sm" >
<thead>
<tr>
<th>VERSION</th>
<th>DATE</th>
<th>UUID</th>
</tr>
</thead>
<tbody>
{this.state.results.map(result =>
<tr key={result.fileId}>
<td>{result.VERSION}</td>
<td>{result.ORIGIN}</td>
<td>{result.UUID}</td>
</tr>
)}
</tbody>
</Table>
</div>
</div>
);
}
}
也许我可以使用一些js
脚本,但告诉我如何使用它,我是新与ReactJS
。例如,我的版本是0.26.8
。
答
我会在这里使用lodash的sortBy()
功能:
https://lodash.com/docs/4.17.4#sortBy
const sorted = _.sortBy(this.state.results, 'VERSION')
然后在sorted
代替this.state.results
答
地图只需确保this.state.results
被渲染之前正确排序。
最简单的方法很可能是类似以下内容:
{this.state.results.sort((a, b) => a.VERSION - b.VERSION).map(result =>
<tr key={result.fileId}>
<td>{result.VERSION}</td>
<td>{result.ORIGIN}</td>
<td>{result.UUID}</td>
</tr>
)}
编辑:既然你说,该版本不是一个数值,而是一个semantic versioning串,你的排序功能需要更复杂一点。我建议你看看this SO question,或者使用覆盖该用例的one of the many available libraries。
答
const sorted = results.sort((x,y) => {
return parseInt(x.VERSION) - parseInt(y.VERSION);
});
按升序排序
+0
我的版本看起来像:0.22.6,不只是一个数字。我忘了将它添加到描述中。已更新,对不起。 –
我的版本是这样的:'0.22.6',不仅是一个数字。我忘了将它添加到描述中。已更新,对不起。 –
@AleksanderSołop查看我的编辑 – Timo