简体   繁体   English

如何按升序和降序对列进行排序?

[英]how sort columns in ascending and descending order?

i am created table using array of objects and now i didnot undestand How We sort table in ascending and descnding order by clicking on column name in reactjs.我是使用对象数组创建的表,现在我不明白我们如何通过单击reactjs 中的列名按升序和降序对表进行排序 I am tried lot of concepts on stackoverflow but it seems it doesnot useful for this one.我在stackoverflow上尝试了很多概念,但它似乎对这个没有用。 This is very silly question but I am stopped on this from many days.这是一个非常愚蠢的问题,但我已经停止了很多天。

 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
  • You need to switch the onChange handler to onClick .您需要将onChange处理程序切换到onClick
  • add some state to store the last sort direction;添加一些 state 来存储最后的排序方向;
  • Use the Array sort() method, but take care not to mutate your state.使用 Array sort()方法,但注意不要改变 state。
  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 });
}

To be able to sort on any of the columns, I would make the following change:为了能够对任何列进行排序,我将进行以下更改:

  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 });
  }

And add an appropriate onClick handler for each column heading.并为每个列标题添加适当的onClick处理程序。

<th onClick={() => this.sort('id')}>ID</th>
<th onClick={() => this.sort('fullName')}>Full Name</th>
<th onClick={() => this.sort('email')}>Email</th>

编辑黎明纸 1bh7t

Add a state variable for ascending or descending sort and then in your sort function:添加一个 state 变量用于升序或降序排序,然后在您的排序 function 中:

function Sort(a,b){
    if(this.state.ascending){
        return a.id - b.id
    {
    return b.id - a.id
}

And then in your render function add the sort method before the map:然后在您的渲染中 function 在 map 之前添加排序方法:

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>
              
               

Finally change your onClick to just change the state of ascending/descending:最后将您的 onClick 更改为仅更改 state 的升/降:

 <th onClick={()=>this.setState({ascending: !this.state.ascending)}>ID</th>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 Reactjs 中按升序或降序对数据进行排序? - How to sort data in ascending or descending order in Reactjs? 如何对二维整数数组进行升序和降序排序 - How to sort a 2 dimensional Integer array both ascending order and descending order tinytable如何按降序排序表而不是升序 - tinytable how to sort table in descending order rather then ascending 如何对数组进行升序和降序排序? - How to sort an array ascending and descending? 我如何获得 wordpress 插件,以使来自前端的访问者能够按升序或降序对帖子进行排序 - How can i get a wordpress plugin to enable visitors from frontend to sort posts by ascending order or descending order 如何更改排序 function 以同时接受升序和降序 - How can i change my sort function to both accept ascending order and descending order 如何在angularjs中单击按钮时使用ng重复来按升序和降序排序 - How to sort in ascending alphabetic order and descending alphabetic order with ng repeat on button click in angularjs 如何在JavaScript中按字母顺序(升序和降序)排序 - How to sort by alphabetically (ascending and descending) in JavaScript 如何在Ramda中组成升序/降序 - How to compose an ascending/descending sort in Ramda 单击时按降序和升序排序 - Sort descending and ascending on click
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM