gpt4 book ai didi

javascript - React TypeScript 如何遍历一个对象?

转载 作者:行者123 更新时间:2023-12-05 00:46:18 25 4
gpt4 key购买 nike

这是特定于 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: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Profile'. No index signature with a parameter of type 'string' was found on type 'Profile'.

我尝试使用 Object.valuesfilter 但无法修复它。

最佳答案

试试

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>
)
}

关于javascript - React TypeScript 如何遍历一个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61309105/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com