如何使用地图功能做出3列网格反应

Rob*_*gar 5 javascript arrays reactjs bootstrap-4

我有一些卡片,我想让它看起来像这样

[] [] []
[] [] []
[] [] []
...
...

Run Code Online (Sandbox Code Playgroud)

我在使用地图功能渲染项目时遇到问题。我已经尝试过这个,但它不起作用。对于每个索引,如果索引可被 3 整除,我想创建新行。我怎样才能做到这一点?

                {products.map((val, index) => (
                    { index%3 == 0 ? <div className="row mx-auto"> : null}
                    <Card>
                      {val.description}
                    </Card>
                    { index%3 == 0 ? </div> : null}
                ))}
Run Code Online (Sandbox Code Playgroud)

任何帮助,将不胜感激。

Dre*_*ese 8

问题

您不能像这样有条件地呈现打开/关闭标签。

解决方案

将数组分成数组的数组并映射行,然后映射列。

分块函数示例:

const arrayChunk = (arr, n) => {
  const array = arr.slice();
  const chunks = [];
  while (array.length) chunks.push(array.splice(0, n));
  return chunks;
};
Run Code Online (Sandbox Code Playgroud)

映射示例:

{arrayChunk(products, 3).map((row, i) => (
  <div key={i} className="row mx-auto">
    {row.map((col, i) => (
      <span key={i}>[{col}]</span>
    ))}
  </div>
))}
Run Code Online (Sandbox Code Playgroud)

const arrayChunk = (arr, n) => {
  const array = arr.slice();
  const chunks = [];
  while (array.length) chunks.push(array.splice(0, n));
  return chunks;
};
Run Code Online (Sandbox Code Playgroud)
{arrayChunk(products, 3).map((row, i) => (
  <div key={i} className="row mx-auto">
    {row.map((col, i) => (
      <span key={i}>[{col}]</span>
    ))}
  </div>
))}
Run Code Online (Sandbox Code Playgroud)