我如何使用地图呈现项目列表但每 3 个项目分组?

the*_*uls 4 javascript arrays reactjs

我有一个数组中的一长串项目。这些需要在一个组件中呈现,这应该很好而且很花哨。但是,我需要在每 3 个项目中由另一个组件包装这些。

所以,如果我只是渲染项目,它看起来像这样:

return (
  <div>
    items.map((x, index) => {
      <span key={index}>{x}</span>
    })
  </div>
)
Run Code Online (Sandbox Code Playgroud)

但基本上,我希望每三个项目都被包裹在一个具有特殊类的 div 中,所以是这样的:

return (
  <div>
    <div className='group-of-3'>
      <span>Item 1</span>
      <span>Item 2</span>
      <span>Item 3</span>
    </div>
    <div className='group-of-3'>
      <span>Item 4</span>
      <span>Item 5</span>
      <span>Item 6</span>
    </div>
    .
    .
    .
  </div>
)
Run Code Online (Sandbox Code Playgroud)

这样做的理想方法是什么?请记住,项目的数量确实会发生变化,因此手动进行操作是不可能的。

jo_*_*_va 5

使用纯 JavaScript,您可以使用Array.reduce()您的项目创建子数组。然后在您的项目上映射两次:

const group = (items, n) => items.reduce((acc, x, i) => {
  const idx = Math.floor(i / n);
  acc[idx] = [...(acc[idx] || []), x];
  return acc;
}, []);

function Example({ items }) {
  return (
    <div>{group(items, 3).map(children =>
        <div className='group-of-3'>
          {children.map((x, i) => <span key={i}>{x}</span>)}
        </div>
    )}</div>
  );
}

ReactDOM.render(
  <Example items={[1, 2, 3, 4, 5, 6, 7, 8]} />,
  document.getElementById('root')
);
Run Code Online (Sandbox Code Playgroud)
.group-of-3 {
  border: 1px solid black;
  padding: 5px;
  margin: 5px;
  width: 50px;
  text-align: center;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
Run Code Online (Sandbox Code Playgroud)