this.questions = [{
"id" : 1 ,
"question" : "question",
"answers" : ["A","B","C","D"],
},
{
"id" : 2,
"question" : "question",
"answers" : ["A","B","C","D"],
}]
我有一个像这样的对象。我正在将这些数据呈现给一个表。使用此代码;
renderTable(result) {
return (
<table>
<tr><td>{result.id}</td><td>{result.question}</td></tr>
<tr><td>Answers</td>{result.answers}</td></tr>
</table>)
}
render() {
return (
<Row>
{this.questions.map(this.renderTable.bind(this))}
</Row>)
}
问题:
我想将answers数组的每个元素呈现给不同的表数据标记。 我怎么能这样做?
此致
答案 0 :(得分:0)
使用地图迭代答案,然后动态创建td的
renderTable(result) {
return (
<table>
<tr><td>{result.id}</td><td>{result.question}</td></tr>
<tr><td>Answers</td>{result.answers.map(function(value,index){
return(<td>{value}</td>);
})}</tr>
</table>)
}
render() {
return (
<Row>
{this.questions.map(function(value,index){
this.renderTable.bind(this,value);
});
}
</Row>)
}
答案 1 :(得分:0)
renderTable(){
const answers = (items) => {
return items.map((item) => {
return ( <td>{item}</td>)
})
}
return this.questions.map((result) => {
return (
<table>
<tr><td>{result.id}</td><td>{result.question}</td></tr>
<tr><td>Answers</td>
{this.answers(result.answers)}
</tr>
</table>)
)
})
}
render() {
return (
<Row>
{this.renderTable()}
</Row>
)
}
你可以这样做,使用map来迭代答案
答案 2 :(得分:0)
据我所知,没有必要创建renderTable(result)。我在下面写了代码,请告诉我它是否有帮助。
class MyComponent extends React.Component{
render() {
const data = [{
"id" : 1 ,
"question" : "question1",
"answers" : ["A1","B1","C1","D1"],
},
{
"id" : 2,
"question" : "question2",
"answers" : ["A2","B2","C2","D2"],
},
{
"id" : 3,
"question" : "question3",
"answers" : ["A3","B3","C3","D3"],
},
{
"id" : 4,
"question" : "question4",
"answers" : ["A4","B4","C4","D4"],
}];
const listItems = data.map((row) =>
<li>
<table>
<tr><td>{row.id}</td><td>{row.question}</td></tr>
<tr><td>Answers:{row.answers}</td></tr>
</table>
</li>
);
return (
<div>
<ul>
{listItems}
</ul>
</div>
);
}
}