React动态表行

时间:2017-08-17 12:29:45

标签: reactjs html-table

我有一个反应表,它映射在一个对象数组上。我还想映射这些对象的一个​​属性以创建更多行。我要映射的对象属性也是一个对象数组。所以我的数据看起来像这样:

[
  {id:1,name:"fakeName",children:[{id:10,name:"fakeChildName"}]},
  {id:2,name:"fakeName2",children:[{id:11,name:"fakeChildName11"}]}
]

然后,在我的render()中,我将其放在一张桌子中:

<tbody>
  {myArray.map(row => (
    <tr key={`row-${row.name}`}>
      <td>
        <div className="parent">{row.id}</div>
      </td>
      <td>{row.name}</td>
      <td />
      <td />
      <td />
    </tr>
  ))}
</tbody>

这很好。我想遍历row.children对象以创建更多行来填充同一个表体的第3,4和5列。所以我这样做了:

<tbody>
  {myArray.map(row => (
    <tr key={`row-${row.name}`}>
      <td>
        <div className="parent">{row.id}</div>
      </td>
      <td>{row.name}</td>
      <td />
      <td />
      <td />
    </tr>
    {row.children.map(childRow => (
      <tr key={`row-child-${childRow.name}`}>
        <td />
        <td />
        <td>{childRow.id}</td>
        <td>{childRow.name}</td>
        <td><button>myButton</button></td>
      </tr>
    ))}
  ))}
</tbody>

当我添加该部分时,我在我{row.children.map...说它预期会有逗号的行上会出现意外的令牌错误。我不确定如何正确地做到这一点。

2 个答案:

答案 0 :(得分:3)

您正在关闭<tr>之前的行{row.children.map...,这是非法的JSX。您可以改为返回JSX数组:

{myArray.map(row => ([
  <tr key={`row-${row.name}`}>
    <td>
      <div className="parent">{row.id}</div>
    </td>
    <td>{row.name}</td>
    <td />
    <td />
    <td />
  </tr>,
  {...row.children.map(childRow => (
    <tr key={`row-child-${childRow.name}`}>
      <td />
      <td />
      <td>{childRow.id}</td>
      <td>{childRow.name}</td>
      <td><button>myButton</button></td>
    </tr>
  ))}
]))}

你可以说这会使事情变得令人讨厌,所以我更喜欢清晰而简洁:

{myArray.map(row => {
  const parentRow = (
    <tr key={`row-${row.name}`}>
      <td>
        <div className="parent">{row.id}</div>
      </td>
      <td>{row.name}</td>
      <td />
      <td />
      <td />
    </tr>
  );
  const childrenRows = row.children.map(childRow => (
    <tr key={`row-child-${childRow.name}`}>
      <td />
      <td />
      <td>{childRow.id}</td>
      <td>{childRow.name}</td>
      <td><button>myButton</button></td>
    </tr>
  ));

  return [parentRow, ...childrenRows];
})}

答案 1 :(得分:0)

您应该返回single React element

试试这个(div是单个React元素):

<tbody>
  {myArray.map(row => {
    return (
      <div>
        <tr key={`row-${row.name}`}>
          <td>
            <div className="parent">{row.id}</div>
          </td>
          <td>{row.name}</td>
          <td />
          <td />
          <td />
        </tr>
        {row.children.map(childRow => (
          <tr key={`row-child-${childRow.name}`}>
            <td />
            <td />
            <td>{childRow.id}</td>
            <td>{childRow.name}</td>
            <td><button>myButton</button></td>
           </tr>
         ))}
       </div>
     )
    })}
  </tbody>