对特定列进行排序

时间:2018-05-29 07:30:13

标签: javascript reactjs

我有一个数组items[],其中有四个字段nameorigindestinationseats。 我想按字母顺序对点标题进行排序,即Name

继承我的代码片段

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

Stuff.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;

Table.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 个答案:

答案 0 :(得分:1)

我没有详细了解ReactJS,您需要自己实施。这个想法很简单:

  1. 您为标题创建了一个事件处理程序,如(onClick)=&#34; sortByName()&#34;
  2. 通过将数据传入其中来定义函数sortByName,并手动对其进行排序,您可以使用Array.sort()来实现此目的。
  3. 更新状态将使React重新渲染部分有更新

答案 1 :(得分:0)

我希望这可以回答您的问题:

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/

相关问题