我有ControlSection一个组件,它的道具之一是statistics对象道具。我想显示<h2>对象的所有键和值。我该怎么做?
控制部分:
const ControlSection = ({ statistics }) => {
return (
<div className='gameStatistics'>
{
Object.keys(statistics).forEach(key =>
<h2>key: statistics[key]</h2>
)
}
</div>
)
}
Run Code Online (Sandbox Code Playgroud)
统计示例:
const statistics = {
Score: score,
Level: level,
Best: bestScore,
};
Run Code Online (Sandbox Code Playgroud)
ggo*_*len 14
forEach返回undefined。Use 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>
);
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6991 次 |
| 最近记录: |