【发布时间】:2019-12-12 11:24:37
【问题描述】:
我有以下 React 组件,它从对象数组生成 HTML 表。应该显示的列是通过tableColumns 属性定义的。
当循环 items 并显示正确的列时,我必须使用 tableColumn 对象 ({item[column.key]}) 中的 key 属性,但 typescript 会生成以下错误:
元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型“{}”。 在“{}”类型上找不到带有“字符串”类型参数的索引签名。
我能做些什么来解决这个问题?我迷路了
我如何调用组件:
<TableGridView
items={[
{
id: 1,
name: 'John Doe',
email: 'john@doe.de'
},
{
id: 2,
name: 'Lorem ipsum',
email: 'lorem@ipsum.com',
}
]}
tableColumns={[
{
key: 'id',
label: 'ID',
},
{
key: 'name',
label: 'Name',
}
]}
/>
我的组件:
export type TableColumn = {
key: string,
label: string,
};
export type TableGridViewProps = {
items: object[],
tableColumns: TableColumn[]
};
const TableGridView: React.FC<TableGridViewProps> = ({ tableColumns, items }) => {
return (
<table>
<tbody>
{items.map(item => {
return (
<tr>
{tableColumns.map((column, index) => {
return (
<td
key={column.key}
className="lorem ipsum"
>
{item[column.key]} // error thrown here
</td>
);
})}
</tr>
);
})}
</tbody>
</table>
);
}
【问题讨论】:
标签: javascript reactjs typescript