javascript - 在 React 中使用 2D map 打印棋盘

标签 javascript reactjs

我对 react 还很陌生,但我没有使用常见的 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

Current render

enter image description here

最佳答案

在使用 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}
                />
            );
        });
    });
};

注意:如果您想要棋盘的二维数组,请将flatMap 更改为map

关于javascript - 在 React 中使用 2D map 打印棋盘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69689418/

相关文章:

javascript - reactjs 中的渲染函数

javascript - 从 CDN 导入 Materializecss 并让选择下拉菜单在 ReactJS 中工作?

javascript - $.ajax成功调用原型(prototype)函数报错

JavaScript 正则表达式搜索

javascript - Openlayers 标记在多个标记上单击事件

javascript - react JS : Rendering object keys and its values

javascript - 不渲染组件 onClick

javascript - React-Router-Redux 和 React-Bootstrap

javascript - 为什么我不能使用 JavaScript 迭代保存在 html 数据选择器上的数组?

javascript - Sendgrid SMTP API 在发送邮件时不替换替换标签