我正在尝试使用通过API检索的列表对表进行排序。我在react +打字稿中这样做。我面临类型错误。请帮帮我。下面是我的代码。 因此,通过将鼠标悬停在Name,Type,Color上,可以对此进行排序,但是排序不起作用。请仔细阅读代码并帮助我进行排序。
export interface VehicleListProps {
vehicle: VehicleState;
listVehicles: (limit: number, skip: number) => void;
addVehicle: (id: string) => void;
deleteVehicle: (id: string, limit: number, skip: number) => void;
}
const Row = ({name, type , color }) => (
<div className="row">
<div>{name}</div>
<div>{type}</div>
<div>{color}</div>
</div>
);
const VehicleList: React.FC<VehicleListProps> = (props) => {
constructor(props); {
this.state = {
data: vehicle
};
this.compareBy = compareBy.bind(this);
this.sortBy = sortBy.bind(this);
}
function compareBy(key) {
return function (a, b) {
if (a[key] < b[key]) return -1;
if (a[key] > b[key]) return 1;
return 0;
};
}
function sortBy(key) {
let vehicle = [...this.state.data];
vehicle.sort(this.compareBy(key));
this.setState({data: vehicle});
}
const rows = this.state.data.map( (rowData) => <Row {...rowData} />);
return (
<div>
<div className="row gap-20 masonry pos-r">
<Table id="dataTable" className="table table-hover table-striped">
<thead className="thead-dark" >
<tr>
<th onClick={() => this.sortBy('name')}>Name</th>
<th onClick={() => this.sortBy('type')}>Type</th>
<th onClick={() => this.sortBy('color')}>Color</th>
<th></th>
</tr>
</thead>
<tbody>{
vehicle.page.collection.map((vehicle, idx) => {
return (
<tr key={idx}>
<td><a className="vehicleName" href={`/vehicles/${vehicle.id}`}>{vehicle.name}</a></td>
<td>{vehicle.type}</td>
<td>{vehicle.color}</td>
</tr>
)
})
}</tbody>
</Table>
</div>
</div>
</div>
);
}