React.js is a plain javascript.(React.js是一个普通的javascript。)
You should use Array.prototype.sort
.(您应该使用Array.prototype.sort
。) Created stackblitz for you.(为您创建了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'));
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…