javascript - React TypeScript 如何遍历一个对象?
问题描述
这是特定于 React 的。
我有一个这样的对象:
interface Profile {
name: string;
title: string;
}
const NewPerson: Profile = {
name: "John Smith",
title: "Software Engineer"
}
我想在 React 组件中返回该对象的键值对,如下所示:
function MyFunc() {
return (
<div>
{
Object.keys(NewPerson).map((key) => (
<div>{key}: {NewPerson[key]}</div>
))
}
</div>
)
}
但是,我可以访问它们,key
但不能访问它的值。我有这个错误:
TS:元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型“配置文件”。在“配置文件”类型上找不到具有“字符串”类型参数的索引签名。
我尝试使用Object.values
但filter
无法修复它。
解决方案
尝试
interface Profile {
name: string;
title: string;
[key: string]: string;
}
const NewPerson: Profile = {
name: "John Smith",
title: "Software Engineer"
}
function MyFunc() {
return (
<div>
{
Object.keys(NewPerson).map((key: keyof Profile) => (
<div>{key}: {NewPerson[key]}</div>
))
}
</div>
)
}
推荐阅读
- bash - 在执行其他命令时将 ssh 输出重定向到文件
- vue.js - 如何正确使用 vue 路由器上的元道具?
- php - 如何使用 FollowUpBoss Api 获取客户的自定义字段值
- codenameone - 使用 Codename One 管理 http 错误代码
- matlab - 如何将多个点对象存储在数组或结构中?
- c++ - 在没有系统调用(管道)的线程之间使用 std::istream 和 std::ostream
- python - Strange syntax and error when executing lambda function with multiple arguments
- r - 如何以有效的方式根据其他索引变量的条件创建变量?
- python-2.7 - 使用正则表达式获取匹配词的索引
- shopify - 向 Shopify 自定义主题添加向下滚动按钮