对特定列进行排序

IT技术 javascript reactjs
2022-07-18 01:23:05

我有一个数组items[],它有四个字段name, origin, destination, seats我想按字母顺序对表格标题的名称进行排序,即Name

这是我的代码片段

带有数组声明变量并将值传递给 form.js 的 JS 文件

东西.js

import React, { Component } from 'react';
import './App.css';
import Tab from './Table';
import Form from './Form';

class Stuff extends Component {
  constructor() {
    super();

    this.state = {
      name: '',
      origin: '',
        destination: '',
          seats: '',
      items: []
    }
  };

  handleFormSubmit = (e) => {
    e.preventDefault();

    let items = [...this.state.items];

    items.push({
      name: this.state.name,
      origin: this.state.origin,
      destination: this.state.destination,
      seats: this.state.seats
    });

    this.setState({
      items,
      name: '',
      origin: '',
      destination: '',
      seats: ''
    });
  };

  handleInputChange = (e) => {
    let input = e.target;
    let name = e.target.name;
    let value = input.value;

    this.setState({
      [name]: value
    })
  };

  render() {
    return (
      <div className="App">

        <Form handleFormSubmit={ this.handleFormSubmit }
          handleInputChange={ this.handleInputChange }
          newName={ this.state.name }
          newOrigin={ this.state.origin }
          newDestination={ this.state.destination }
          newSeats={ this.state.seats } />
<Tab items={ this.state.items }/>

      </div>
    );
  }
}

export default Stuff;

表.js

import React, { Component } from 'react';
import { Table } from 'reactstrap';

class Tab extends React.Component {

  render() {
    const items = this.props.items;



  return (

      <Table striped>
             <thead>
               <tr>

                 <th  >Name</th>
                 <th>Origin</th>
                 <th>Destination</th>
                 <th>Seats</th>

               </tr>
             </thead>
             <tbody>
             {items.map(item => {
  return (

               <tr>

                 <td>{item.name}</td>
                 <td>{item.origin}</td>
                 <td>{item.destination}</td>
                 <td>{item.seats}</td>

               </tr>
             );
           })}

             </tbody>
           </Table>

    );
  }
}


export default Tab;

有没有什么方法可以让我点击表格中的名称标题时,它会根据名称进行排序?

谢谢你

2个回答

ReactJS的细节我不赘述,需要自己实现。这个想法很简单:

  1. 您为 (onClick)="sortByName()" 之类的标头创建事件处理程序
  2. 通过将数据传递给它来定义您的函数 sortByName,并手动对其进行排序,您可以使用 Array.sort() 来实现这一点。
  3. 更新状态将使 React 重新渲染有更新的部分

我希望这能回答您的问题:

const items = [
    {
    name: 'C',
    quantity: 2
  },
  {
    name: 'B',
    quantity: 3
  },
  {
    name: 'A',
    quantity: 8
  }
];

console.log(items);

items.sort((a,b) => {
    const name1 = a.name.toLowerCase(), name2 = b.name.toLowerCase();
    return name1 === name2 ? 0 : name1 < name2 ? -1 : 1;
});

console.log(items);

https://jsfiddle.net/abhikr713/r6L2npfL/1/