我是React的新手。如何使用“地图”功能在两列中列出来自两个不同数组的元素?
state = {
dates: ["2000", "2001", "2002"],
cases: ["1", "2", "3"]
}
render(){
return (
<thead>
<tr>
<th>Date</th>
<th>Cases</th>
</tr>
</thead>
<tbody>
{this.state.dates.map(el =>
<tr>
<td>{el}</td>
</tr>
)} // I want to list elements from "cases" array like this but in the second column
</tbody>
</table>
</div>)
}
}
您可以使用地图功能中的index
参数并访问案例数组
<tbody>
{this.state.dates.map((el, index) => (
<tr>
<td>{el}</td>
<td>{this.state.cases[index]}</td>
</tr>
))}{" "}
</tbody>;
如果您总是假设dates
和cases
的长度相同,那么您可以这样做:
{this.state.dates.map((el, index) => (
<tr>
<td>{this.state.dates[index]}</td>
<td>{this.state.cases[index]}</td>
</tr>
))}