如何在像AngularJS这样的ReactJS中排序

时间:2019-11-28 12:46:29

标签: javascript reactjs

在AngularJS中可以对像这样的ng-repeat="user in users | orderBy: order"数组进行排序,我需要知道如何在ReactJS中做到这一点,这是AngularJS中的一个例子

const myApp = angular.module('myApp', [])
myApp.controller('myAppController', ['$scope', $scope => {
  $scope.users = [
    { name: 'Maria', age: 16, color: 'red' },
    { name: 'Mike', age: 18, color: 'black' },
    { name: 'John', age: 23, color: 'green' },
    { name: 'Liza', age: 21, color: 'yellow' }
  ]
  $scope.order = 'name'
  $scope.orderBy = orderBy => $scope.order = orderBy
}])
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<table ng-app="myApp" ng-controller="myAppController">
  <tr>
    <th ng-click="orderBy('name')">Name</th>
    <th ng-click="orderBy('age')">Age</th>
    <th ng-click="orderBy('color')">Color</th>
  </tr>
  <tr ng-repeat="user in users | orderBy: order">
    <td>{{user.name}}</td>
    <td>{{user.age}}</td>
    <td>{{user.color}}</td>
  </tr>
</table>

1 个答案:

答案 0 :(得分:2)

React.js是普通的javascript。
您应该使用Array.prototype.sort
为您创建了stackblitz

import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';

class App extends Component {
  constructor() {
    super();
    this.state = {
      name: 'React',
      order: 'name',
      users: [
        { name: 'Maria', age: 16, color: 'red' },
        { name: 'Mike', age: 18, color: 'black' },
        { name: 'John', age: 23, color: 'green' },
        { name: 'Liza', age: 21, color: 'yellow' }
      ]
    };
    this.sort = this.sort.bind(this); 
    this.setOrder = this.setOrder.bind(this); 
  }

  setOrder(e) {
    const order = e.target.dataset.order;

    this.setState({order});
  }

  sort(a, b) {
    if (!this.state.order) return 0;
    if(a[this.state.order] < b[this.state.order]) { return -1; }
    if(a[this.state.order] > b[this.state.order]) { return 1; }
    return 0;
  }

  render() {
    return (
      <div>
        <button data-order='name' onClick={this.setOrder}>by name</button>
        <button data-order='color' onClick={this.setOrder}>by color</button>
        {this.state.users.sort(this.sort).map(user => <div>name: {user.name}, color: {user.color}</div>)}
      </div>
    );
  }
}

render(<App />, document.getElementById('root'));