我有ControlSection
个组件,它的道具之一是statistics
对象道具。我想用<h2>
显示对象的所有键和值。我该怎么办?
ControlSection:
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,
};
答案 0 :(得分:4)
forEach
返回undefined
。使用Array#map
,它为新数组中的每个项目返回JSX。
JSX还需要使用{ }
大括号来将文本评估为JS。
由于您正在创建一系列<h2>
元素,因此React需要在元素上设置key
属性。使用来自对象的key
就足够了,因为可以保证它们是唯一的字符串。但是,您可以考虑使用列表(<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>
);
};