【问题标题】:How to sort an aray in ReactJS like AngularJS如何在 React JS 中像 AngularJS 一样对数组进行排序
【发布时间】:2019-11-28 12:46:29
【问题描述】:

在 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>

【问题讨论】:

标签: javascript reactjs


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2013-11-08
    • 1970-01-01
    • 2020-04-13
    • 2014-11-07
    • 2013-12-16
    • 2020-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多