如何循环遍历对象并在 React.js 中创建子组件

How to loop thorough object and create child component in React.js

我是 React.js 的新手,在整个子组件循环中卡住了。我有一个对象,我需要遍历它,它应该使用该对象的值创建子组件。提前谢谢你

var o = {
    playerA: {
        name: 'a',
    },

    playerB: {
        name: 'b',
    }
};


var Players = React.createClass({
    getPlayers: function(){
        return o;
    },    

    render: function() {
        return (
            <div>
                <div className="row"> Players</div>
                {this.getPlayers()}
                <Player /> 
            </div>
        );
    }
});


var Player = React.createClass({    
    render: function(){
        return (
            <div className="row" > player {this.name} < /div>
        )
    }
});

React.render(<Players />, document.getElementById('container'));

结果应该是:

选手a

选手b


我已经 fiddle 设置在: http://jsfiddle.net/rexonms/7f39Ljbj/

首先,您将使用 .map 遍历数据,以便您可以 return 为每个项目标记(子组件)。在子组件标记中,您在属性中传递该项目的数据。

{Object.keys(yourObject).map(function(key) {
  return (
    // Add a key to the list item, it is mandatory from react
    // What the key consists of if it's the id or not is up to you
    // it needs to be unique though
    <ChildComponent key={key} data={yourObject[key]}/>
  );
})}

然后子组件的标记可以通过绑定 this.props.data.

使用该数据
<div>Player: {this.props.data.name}</div>

您不必为 attribute/property 使用名称“数据”。 info={yourObject[key]}this.prop.info 之类的东西同样有效。

Working JS Fiddle here.