最佳答案
我有以下 React 组件,它可以从对象数组生成 HTML 表。应该显示的列是通过 tableColumns
属性定义的。
当循环通过 items
并显示正确的列时,我必须使用来自 tableColumn
对象({item[column.key]}
)的 key
属性,但是输入法会产生以下错误:
元素隐式具有“ any”类型,因为类型“ string”的表达式不能用于索引类型“{}”。 在“{}”类型上找不到带有类型为“ string”的参数的索引签名。
What could I do to fix this? I'm lost
我如何调用组件:
<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',
}
]}
/>
My Component:
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>
);
}