reactjs - 如何在使用打字稿进行排序时解决类型错误?
问题描述
我正在尝试使用通过 API 检索的列表对表进行排序。我在 react + typescript 中这样做。我正面临类型错误。请帮助我。下面是我的代码。因此,通过将鼠标悬停在 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>
);
}
解决方案
推荐阅读
- android - Android Fragment:进入和返回的不同动画
- java - 如何修复错误:未找到 ID 为“com.google.gms:google-services:4.2.0”的插件
- r - 提取以特定预定义字符串正则表达式开头的行?
- python - 我不能在 WSL Ubuntu 上使用 pip
- c# - Mongo DB C# 驱动程序 - 如何定义没有属性的复合 ID?
- npm - npm 组存储库在 nexus 3 中的意外包解析行为
- django - DJANGO 如何进行可以在两个值之间进行过滤的 Q 查询?
- docker - 我尝试在 docker 中部署 gRPC (go) 服务器并在本地端口中公开端口,但端口绑定不起作用
- bash - 为非交互式 shell 获取 .bashrc 的正确方法
- python - 为什么此代码在尝试在 for 循环中输入时显示运行时错误?