我是 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
遍历数据,以便您可以为每个项目返回标记(子组件)。在子组件标记中,您在属性中传递该项目的数据。
{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]}/>
);
})}
然后子组件的标记可以通过绑定(bind) this.props.data
使用该数据。
<div>Player: {this.props.data.name}</div>
您不必为属性/特性使用名称“数据”。像 info={yourObject[key]}
和 this.prop.info
一样有效。
关于javascript - 如何在 React.js 中遍历对象并创建子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29724473/