我是构建应用程序和编码的新手,作为一个业余项目,我正在尝试使用 React 和 JavaScript 制作一个棋盘。我目前正试图找出一种方法,在下面的 Chessboard 组件的 2D for 循环中创建一个唯一的 id 键:
这是 Tile 组件的代码
import './Tile.css'; const WhiteTile = () => { return( <div className='TileWhite'></div> ) } const AquaTile = () => { return( <div className='TileAqua'></div> ) } const ENUM_OBJECT = { whiteTile: <WhiteTile/>, aquaTile: <AquaTile/>, }; function Tile({tileType}) { return ENUM_OBJECT[tileType] } export default Tile;
这是棋盘组件的代码
import React from 'react'; import '../ChessBoard/Chessboard.css' import Tile from './Tile'; function ChessBoard() { const xCoordinates = ["a", "b", "c", "d", "e", "f", "g", "h", "0"]; const yCoordinates = ["0", "1", "2", "3", "4", "5", "6", "7", "8"]; const coordinatesBoard = []; const RenderCoordinates = () => { for(let y = yCoordinates.length; y > 0; y--) { for(let x = 0; x < xCoordinates.length - 1; x++) { if(x % 2 === 0) { coordinatesBoard.push(<Tile tileType={"whiteTile"} key={''}></Tile>); } else { coordinatesBoard.push(<Tile tileType={"aquaTile"} key={''}></Tile>); } } } return coordinatesBoard; } return(<div className="App"> {<RenderCoordinates/>} </div>) } export default ChessBoard;
我之前尝试过使用地图功能
const RenderTiles = () => { const cBoard = coordinatesBoard.map((xyCoordinates, index) => { if(index % 2) { return( <div className ="Tile1" key={index}> {xyCoordinates} </div> ) } else { return( <div className ="Tile2" key={index}> {xyCoordinates} </div> ) } }); return cBoard }
还研究了 useState
const [counter, setCounter] = useState(0); const increment = () => { setCounter(counter + 1); }
尝试在这里插入计数器,但遇到无限循环(来自棋盘函数)
coordinatesBoard.push(<Tile tileType={"whiteTile"} key={counter + 1}></Tile>);
我期望每次将图块推到棋盘上时计数器都会增加 请帮忙。
P粉4516148342023-09-15 09:01:53
可以使用基本的随机字符串生成器(并不总是保证唯一,但它非常随机)
function randomString() { const possibleChars = 'abcxyz123' const length = 10 const randString = [] for (let i = 0; i <= length; i++) { const randomChar = possibleChars[Math.floor(Math.random() * possibleChars.length)] randString.push(randomChar) } return randString.join('') } console.log(randomString()) // "3zb1baxbbyy"