0

在 React 应用程序中使用 map 方法遍历十几个或更多项目。每行需要 4 列,所以在第 4 列之后,结束行并创建新行

{index % 4===0 && </div><div className="row">}

但我不能这样做,因为那不是有效的 JSX。我猜有更好的方法来做到这一点。

4

3 回答 3

1

你可以试试这个


const data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14];
const componentArray = [];

export default function App() {
  const formComponents = () => {
    data.forEach((d, i) => {
      let index = Math.floor(i / 4);
      componentArray[index] = [
        ...(componentArray[index] || []),
        <span key={d}>{d}</span>
      ];
    });
    console.log(componentArray);
    return componentArray;
  };

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      {/* <NewDevicePage /> */}
      {formComponents().map((comp, i) => (
        <div key={i}>{comp}</div>
      ))}
    </div>
  );
}


希望这可以帮助。

于 2020-06-26T17:04:36.280 回答
1

做了类似的事情,但如果你只是想控制外观的列数,你可以在技术上忽略这一点,只使用 CSS 来显示你想要的。参考这里:https ://stackoverflow.com/a/45384426/11317072

单击“运行代码片段”以查看它是如何工作的。

// main.js

const App = () => {
  const myData = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
  
  const retrievRowsByColNum = (data, colPerRow) => {
    const rows = [];
    let cols = [];
    for (let i = 0; i < data.length; i++) {
      cols.push(data[i]);
      if ((i + 1) % (colPerRow) === 0) {
        rows.push(cols);
        cols = [];
      }
    }
    if (cols && cols.length > 0) {
      rows.push(cols);
    }
    return rows;
  };
  
  return (<div>{(retrievRowsByColNum(myData, 4)).map((i, k) => i && i.length > 0 && <div key={`row-${k}`}>{i.map((c, ck) => <div key={`key-${ck}`}>col {c}</div>)}<br/></div>)}</div>);
}

ReactDOM.render(<App />, document.querySelector('#root'));
<body>
<div id="root"></div>

<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<script src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>

<script type="text/babel" src="main.js"></script>
</body>

于 2020-06-26T17:19:44.390 回答
1

创建一个列元素数组,每第 4 个元素将数组推入另一个数组(行数组)。您的最终数组将如下所示。

[<tr>{[<td>1</td>, <td>2</td>, <td>3</td>, <td>4</td>]}</tr>];

你可以直接渲染这个数组。

对于参考 - https://reactjs.org/docs/lists-and-keys.html

const Arr = [
  { name: "abc" },
  { name: "def" },
  { name: "ghi" },
  { name: "jkl" },
  { name: "mno" },
  { name: "pqr" }
];

function App() {
  const rows = [];
  let columns = [];
  Arr.forEach((data, index) => {
    if (index % 4 === 0) {
      rows.push(<tr>{columns}</tr>);
      columns = [];
    }
    columns.push(<td>{data.name}</td>);
  });

  // to push the remaining columns
  if(columns.length){
      rows.push(<tr>{columns}</tr>);
  }

  return <table>{rows}</table>;
}

于 2020-06-26T17:00:03.847 回答