reactjs - 在“未知”类型上找不到具有“字符串”类型参数的索引签名
问题描述
我正在尝试创建一个通用表组件,它将接收一组对象并呈现一个表组件。
使用该组件的父组件Cell
需要传递columns
(下面提供的示例)对象,以便决定从数据中呈现哪些字段。
我的问题是,在我的Cell
组件中,我试图为指定列呈现该行的内容,它给了我No index signature with a parameter of type 'string' was found on type 'unknown'.
错误。
这是我的类型定义和 Cell 组件。
注意:Cell
组件接收数据形状的通用类型。
列类型
interface ColumnType<D> {
field: Exclude<keyof typeof D, symbol>; // Excluding symbol as it gives some other errors
}
单元格组件道具
interface ICellProps<D> {
row: D;
col: ColumnType<D>;
}
细胞成分
function Cell<D>(props: ICellProps<D>) {
const { row, col } = props;
return <td>{row[col.field]}</td>; // Error happens here for row[col.field]
}
基本上,对于这个示例数据;
const data = [
{ name: "John", age: 25 },
{ name: "Jane", age: 21 },
];
并为此列列表;
const columns = [
{ field: "name", verbose: "Name" },
{ field: "age", verbose: "Age" },
];
我希望row
对象只接受“姓名”和“年龄”,这应该是这里的情况,因为在Cell
组件内部,col
类型看起来像ColumnType<D>
,但它给了我以下错误:
如果我row[col.field as keyof D]
在错误消失时编写它,但我正在寻找一种解决方案来解决我的类型定义中的问题。我不是 100% 确定这里最好的方法是什么。我想,我设计类型定义的方式应该可以工作,因为row
istype of D
和col.field
is keyof D
。
任何帮助表示赞赏。
解决方案
推荐阅读
- java - javafx Executable .jar 不能很好地工作 Eclipse
- c - 如何将名字和姓氏作为一个并打印在文件中?
- java - 将所有类别的所有列表拆分为子类别?(仅限 Java)
- javascript - 只切换一个菜单/ul 项 Javascript/Jquery
- javascript - 如果没有 Live Server 扩展,则不再创建链接到 HTML 的 Javascript 文件,为什么?
- c++ - 在 C++ 标准中的什么地方指定了在满足以下条件时可以应用空基类优化?
- c - 为什么 db 可以接受超过 1 个字节?
- java - 服务器不向 hashmap 添加地址和端口
- reactjs - 将映射循环内的值分配给循环外的变量
- javascript - html 菜单和子菜单处于活动状态