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

时间:2019-08-20 20:31:29

标签: reactjs

我有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,
};

1 个答案:

答案 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>
    );
};