reactjs 内联条件JSX -预期对应的JSX结束标记< div>

toe95027  于 2023-04-11  发布在  React
关注(0)|答案(1)|浏览(123)

有没有可能使用不带结束标签的内联条件jsx?我需要每隔3个方格插入<div className="board-row">

const gridSquares = squares.map((reference, square) => {
  return (
    <React.Fragment>
      {square % 3 == 0 && square % 3 !== squares.length && (
        <div className="board-row">
      )}
      <Square
        key={square}
        value={squares[square]}
        onSquareClick={() => handleClick(square)}
      />
    </React.Fragment>
  );
});

return (
  <div>
    <div className="status">{status}</div>
    {gridSquares}
  </div>
);

错误:

./src/App.js
Syntax error: C:/Code/Tutorial/src/App.js: Expected corresponding JSX closing tag for <div> (57:4)

  55 |       <Square key={square} value={squares[square]} onSquareClick={() => handleClick(square)} />
  56 | 
> 57 |     </React.Fragment>
     |     ^
  58 |     
  59 |   });
gmol1639

gmol16391#

JSX不像HTML模板,每个元素都被编译成JS,并且必须在结构上有效。
假设您正在尝试创建某种每行包含3个元素的网格,为了简单起见,您可以使用CSS grid,而不必担心标记

return (
  <div>
    <div className="status">{status}</div>
    <div className="board-grid">
      {squares.map((square, index) => (
        <Square
          key={index}
          value={square}
          onSquareClick={() => handleClick(square)}
        />
      ))}
    </div>
  </div>
);
.board-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr); /* 3 squares per row */
}

相关问题