首页 > 解决方案 > 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 中动态完成。
谢谢

标签: javascriptreactjs

解决方案


您可以将所有行存储在一个数组中,然后在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>
  );
}

推荐阅读