javascript - ReactJS 将 2 个数组转换为表格
问题描述
我有 2 个要在表格中呈现的数组。
const arr1 = ["item1","item2","item3","item4"]
const arr2 = ["price1","price2","price3","price4"]
我想将其转换为
<table>
<tr>
<td>item1</td>
<td>price1</td>
</tr>
<tr>
<td>item2</td>
<td>price2</td>
</tr>
<tr>
<td>item3</td>
<td>price3</td>
</tr>
<tr>
<td>item4</td>
<td>price4</td>
</tr>
</table>
注意:保证数组具有相同的长度。
有人可以建议如何在 React 中动态完成。
谢谢
解决方案
您可以将所有行存储在一个数组中,然后在table
:
export default function App() {
const arr1 = ["item1","item2","item3","item4"]
const arr2 = ["price1","price2","price3","price4"]
const rows = []
for (const [index, value] of arr1.entries()) {
rows.push(
<tr key={index}>
<td>{value}</td>
<td>{arr2[index]}</td>
</tr>
)
}
return (
<div className="App">
<table>
<tbody>
{rows}
</tbody>
</table>
</div>
);
}
推荐阅读
- react-native - 反应原生的屏幕方向
- laravel - 奇怪的 Livewire + Turbolinks 行为
- javascript - Prisma:1-N 关系中的过滤和计数
- html - 如何在我的轮播中构建滚动指示器
- python-3.x - 在 Python 函数中调用字符串时出现“TypeError: must be str, not NoneType”错误
- javascript - 为 sveltekit 注册套接字 IO 到 vite
- apache-spark - GroupBy 和 Sum,如果大于零标记行 True
- google-apps-script - 使用代码/脚本的里程计算看起来不是 4 个单元格,只有 2 个。需要帮助
- r - R中的userTimeline没有返回所需数量的推文并给出错误
- r - R Shiny One actionButton 用于多个输出