我對反應還很陌生,但我沒有使用常見的 js for 回圈,而是試圖弄清楚如何使用 .map() 來實作相同的結果。
import React from 'react'
import './styles/Board.css'
import Tile from './Tile'
const Board = () => {
let board = []
printBoard(board)
return (
<div className="board">
{ board }
</div>
)
}
const printBoard = (board) => {
const boardY = [1, 2, 3, 4, 5, 6, 7, 8]
const boardX = ['a','b','c','d','e','f','g','h']
for(let x = 0; x < boardX.length; x ) {
for(let y = boardY.length - 1; y >= 0; --y) {
//saves the position in each square ex: b1
const pos = boardX[x] "" boardY[y]
//paints the squares and the positions
board.push(<Tile key={pos} color={ (x y) % 2 === 0 ? "dark" : "light" } pos={pos} />)
}
}
}
export default Board
當前渲染

uj5u.com熱心網友回復:
import React from "react";
const Board = () => {
const boardY = [1, 2, 3, 4, 5, 6, 7, 8];
const boardX = ["a", "b", "c", "d", "e", "f", "g", "h"];
const reverseY = boardY.reverse();
return (
<div className="board">
{boardX.map((xValues,indexX) =>
reverseY.map((yValues, indexY) => {
const pos = xValues "" yValues;
const colorIndex = indexX indexY;
<Tile key={pos} color={ colorIndex % 2 === 0 ? "dark" : "light" } pos={pos} />
})
)}
</div>
);
};
export default Board;
uj5u.com熱心網友回復:
對map函式執行相同操作時,您需要切換回圈(外部和內部)。并且y必須替換為(boardY.length - (yIndex 1))以獲取遞減索引。
試試下面
const Board = () => {
return <div className="board">{printBoard()}</div>;
};
const printBoard = () => {
const boardY = [1, 2, 3, 4, 5, 6, 7, 8];
const boardX = ["a", "b", "c", "d", "e", "f", "g", "h"];
const boardYRevered = boardY.reverse();
return boardYRevered.flatMap((y, yIndex) => {
return boardX.map((x, xIndex) => {
const pos = `${x}${y}`;
return (
<Tile
key={pos}
color={
(xIndex (boardY.length - (yIndex 1))) % 2 === 0
? "dark"
: "light"
}
pos={pos}
/>
);
});
});
};
注意:如果您想要一個2D array棋盤,請更改flatMap為map。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/333489.html
標籤:javascript 反应
上一篇:Next.js影像樣式通過css
