admin管理员组文章数量:1418065
I am new to React.js and getting stuck loop thorough child ponent. I have an object and I need to loop through it which should create child ponent using the values of that object. Thank you in advance
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'));
The result should be:
player a
player b
I have fiddle set up at: /
I am new to React.js and getting stuck loop thorough child ponent. I have an object and I need to loop through it which should create child ponent using the values of that object. Thank you in advance
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'));
The result should be:
player a
player b
I have fiddle set up at: http://jsfiddle/rexonms/7f39Ljbj/
Share Improve this question edited Apr 21, 2015 at 22:18 tbodt 17k7 gold badges61 silver badges86 bronze badges asked Apr 19, 2015 at 0:32 rexrex 1,0235 gold badges30 silver badges48 bronze badges 1- Have a look at facebook.github.io/react/docs/tutorial.html, "Hook up the data model" – Felix Kling Commented Apr 19, 2015 at 0:39
1 Answer
Reset to default 6First, you'll iterate over the data with .map
so that you can return markup (the child ponent) for each item. In the child ponent markup, you pass the data for that item in an attribute.
{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]}/>
);
})}
The child ponent's markup can then use that data by binding this.props.data
.
<div>Player: {this.props.data.name}</div>
You don't have to use the name "data" for the attribute/property. Something like info={yourObject[key]}
with this.prop.info
is just as valid.
Working JS Fiddle here.
本文标签: javascriptHow to loop thorough object and create child component in ReactjsStack Overflow
版权声明:本文标题:javascript - How to loop thorough object and create child component in React.js - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745250016a2649766.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论