我是使用对象数组创建的表,现在我并没有理解如何通过单击reactjs中的列名来按升序和降序对表进行排序。我在stackoverflow上尝试了很多概念,但似乎对这一概念没有用。这是一个非常愚蠢的问题,但是我从很多天开始就停止了这个工作。
class Hello extends Component {
constructor(props) {
super(props)
this.state = {
search: '',
Data:[
{
id: 1,
fullName: 'abc',
email:'example@gmail.com',
},
{
id: 2,
fullName: 'qps',
email:'qps@gmail.com',
},
{
id: 3,
fullName: 'qwe',
email:'qwe@gmail.com',
},
]
}
}
function Sort(){
//what need to write here;
}
render() {
return (
<div>
<h1>welcome to React</h1>
<table className="table table-hover table-dark">
<tbody>
<tr>
<th onChange={this.Sort.bind(this)}>ID</th>
<th>Full Name</th>
<th>Email</th>
</tr>
{
this.state.Data.map((item,index)=>(
<tr key={item.id}>
<td >{item.id}</td>
<td >{item.fullName}</td>
<td>{item.email}</td>
</tr>
))
}
</tbody>
</table>
</div>
)
}
}
export default Hello
答案 0 :(得分:2)
onChange
处理程序切换为onClick
。sort()
方法,但请注意不要改变状态。 this.state = {
order: 'ASC'
...
function sort() {
let sortedList = [...this.state.Data];
let newOrder = this.state.order === 'ASC' ? 'DESC' : 'ASC';
if (newOrder === 'ASC') {
sortedList.sort((a, b) => a.id - b.id)
} else {
sortedList.sort((a, b) => b.id - a.id)
}
this.setState({ Data: sortedList, order: newOrder });
}
为了能够对任何列进行排序,我将进行以下更改:
function sort(column) {
const sortedList = [...this.state.Data];
const newOrder = this.state.order === "ASC" ? "DESC" : "ASC";
const sortValue = (v1, v2) => {
if (column === 'id') return v1.id - v2.id;
return (v1[column] ?? '')
.toLowerCase()
.localeCompare((v2[column] ?? '').toLowerCase())
}
if (newOrder === "ASC") {
sortedList.sort((a, b) => sortValue(a, b));
} else {
sortedList.sort((a, b) => sortValue(b, a));
}
this.setState({ Data: sortedList, order: newOrder });
}
并为每个列标题添加一个适当的onClick
处理程序。
<th onClick={() => this.sort('id')}>ID</th>
<th onClick={() => this.sort('fullName')}>Full Name</th>
<th onClick={() => this.sort('email')}>Email</th>
答案 1 :(得分:0)
添加状态变量以进行升序或降序排序,然后在您的排序函数中:
function Sort(a,b){
if(this.state.ascending){
return a.id - b.id
{
return b.id - a.id
}
然后在渲染函数中,在地图之前添加sort方法:
const Data = [...this.state.Data]
//...
Data.sort((a,b)=>this.Sort(a,b)).map((item,index)=>(
<tr key={item.id}>
<td >{item.id}</td>
<td >{item.fullName}</td>
<td>{item.email}</td>
</tr>
最后更改您的onClick以仅更改升/降状态:
<th onClick={()=>this.setState({ascending: !this.state.ascending)}>ID</th>