gpt4 book ai didi

reactjs - 如何在React组件中显示对象的键和值

转载 作者:行者123 更新时间:2023-12-02 12:03:54 25 4
gpt4 key购买 nike

我有ControlSection其 Prop 之一是 statistics 的组件对象 Prop 。我想显示 <h2>对象的所有键和值。我该怎么做?

控制部分:

const ControlSection = ({ statistics }) => {
return (
<div className='gameStatistics'>
{
Object.keys(statistics).forEach(key =>
<h2>key: statistics[key]</h2>
)
}
</div>
)
}

统计示例:

const statistics = {
Score: score,
Level: level,
Best: bestScore,
};

最佳答案

forEach返回undefined 。使用 Array#map ,它返回新数组中每个项目的 JSX。

JSX 还需要 { }大括号将文本评估为 JS。

由于您正在创建一系列 <h2>元素,React 需要 key要在元素上设置的属性。使用key来自对象的 s 就足够了,因为它们保证是唯一的字符串。但是,您可以考虑使用列表( <ul><ol> 父元素和 <li> 子元素)作为标题元素的替代方案。

此外,您还可以使用 Object.entries 以比 statistics[key] 稍微更直观的方式访问对象中每对的键和值:

const ControlSection = ({ statistics }) => {
return (
<div className='gameStatistics'>
{
Object.entries(statistics).map(([key, val]) =>
<h2 key={key}>{key}: {val}</h2>
)
}
</div>
);
};

关于reactjs - 如何在React组件中显示对象的键和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57581147/

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