我不知道合适的标题应该是什么,如果不准确,很抱歉。
我有一个处于状态的对象列表:
people: [
{first:'First_1', last:'Last_1', title:' Title_1', company:'Company_1'},
{first:'First_2', last:'Last_2', title:'Title_2', company:'Company_2'},
],
目前,我将每个属性渲染到如下所示的列中:
var first = this.state.people.map(function(person, i) {
return (
<div key={i}>
{person.first}
</div>
)
});
对于last
、title
等也是如此。
然后在返回
中:
return (
<div>
<Grid>
<Row className="show-grid">
<Col md={2}>
{first}
</Col>
<Col md={2}>
{last}
</Col>
<Col md={2}>
{title}
</Col>
<Col md={2}>
{company}
</Col>
<Col md={2}>
Recruiter Phone Screen
</Col>
</Row>
</Grid>
</div>
)
这目前有效,但我有两个问题:
1)每个属性都有一个 var first = ...
、var last = ...
等。
2) 如果缺少一个属性,一切都会变得困惑。 IE - 如果 First_1
没有标题,则将为该记录赋予 Title_2
。
我试图将所有内容合并到一个变量中:
var test = this.state.people.map(function(person, i) {
return {
first: function() {
return (
<div key={i}>{person.first}</div>
)
},
last: function(){
return (
<div>{person.last}</div>
)
}
}
});
并在返回
中:
<Col md={2}>
{test.first}
</Col>
<Col md={2}>
{test.last}
</Col>
等等
这不起作用,但我想知道是否有办法使它起作用?
最佳答案
我会用一个函数来完成此操作,例如:
getParams (param) {
this.state.people.map(function(person, i) {
return (
<div key={i}>
{person[param]}
</div>
)
})
}
在渲染中你将得到这个:
return (
<div>
<Grid>
<Row className="show-grid">
<Col md={2}>
{this.getParams('first')}
</Col>
<Col md={2}>
{this.getParams('last')}
</Col>
<Col md={2}>
{this.getParams('title')}
</Col>
<Col md={2}>
{this.getParams('company')}
</Col>
<Col md={2}>
Recruiter Phone Screen
</Col>
</Row>
</Grid>
</div>
)
关于ReactJS:返回渲染多个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41226775/