我还是React的新人。我从JSON文件中获取了一些数据。我设法让搜索工作。但我也希望能够单击我的名称表头并按名称过滤我的数据。如何使用过滤器来完成这项工作。
import React, { PropTypes } from 'react';
// Mock Data
let MockData = require('./generated.json');
let searchValue = '';
export default class Employees extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
searchValue: '',
sortValue: null
};
this.searchInputChange = this.searchInputChange.bind(this);
this.searchSubmit = this.searchSubmit.bind(this);
}
// Sort function
sortFunction(sortValue, event) {
alert(sortValue);
this.setState({sortValue: sortValue});
}
// Update search value state function
searchInputChange(event) {
this.searchValue = event.target.value;
}
// Search function
searchSubmit(event) {
this.setState({searchValue: this.searchValue});
}
render() {
let sortedEmployeesBySearch = MockData.filter(
(employee) => {
// If state searchValue is not null
if (this.state.searchValue) {
return employee.name.indexOf(this.state.searchValue) !== -1 || employee.gender.indexOf(this.state.searchValue) !== -1 || employee.company.indexOf(this.state.searchValue) !== -1 || employee.email.indexOf(this.state.searchValue) !== -1;
}
else {
return employee;
}
}
);
return (
<div className="container">
<input className="search" type="text" name="search" placeholder="Search table" onChange={this.searchInputChange} />
<input className="searchButton" type="button" value="Search" onClick={this.searchSubmit} />
<table className="employeesList">
<thead>
<tr>
<th onClick={this.sortFunction.bind(this,'name')}>Name</th>
<th onClick={this.sortFunction.bind(this,'gender')}>Gender</th>
<th onClick={this.sortFunction.bind(this,'company')}>Company</th>
<th onClick={this.sortFunction.bind(this,'email')}>E-mail</th>
</tr>
</thead>
<tbody>
{ sortedEmployeesBySearch.map((employee) => (
<tr key={employee.id}>
<td>{employee.name}</td>
<td>{employee.gender}</td>
<td>{employee.company}</td>
<td>{employee.email}</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
}
答案 0 :(得分:0)
您可以按以下方式对数据进行排序: 1)存储状态以进行排序,您已经在进行排序 2)在MockData过滤器之后链接一个排序函数
第二项任务可以通过以下方式完成:
MockData.filter(...).sort((a, b) => {
aVal = a[this.state.sortValue];
bVal = b[this.state.sortValue];
switch(typeof aVal) {
case 'string':
return aVal.localeCompare(bVal);
case 'number':
return aVal - bVal;
default:
throw new Error("Unsupported value to sort by");
}
});
您甚至可以将自定义函数传递给采用这两个值的sort方法,并根据sortValue属性执行自定义排序逻辑。