我有一个数组items[]
,其中有四个字段name
,origin
,destination
,seats
。
我想按字母顺序对点标题进行排序,即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;
当我点击表格中的名称标题时,是否有任何方法可以根据名称进行排序?
谢谢
答案 0 :(得分:1)
我没有详细了解ReactJS,您需要自己实施。这个想法很简单:
答案 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);