React实现Etch-a-Sketch网格涂色游戏功能开发问题咨询
实现方案
修改后可直接实现你需要的两个核心功能:涂色模式切换、一键清空网格,各组件修改代码如下:
1. Board 组件
import React from "react"; import { useState } from "react"; import Buttons from "./Buttons"; import Grid from "./Grid"; function Board() { const [gridSize, setGridSize] = useState(16); // 管理涂色模式:可选值 black / random const [paintMode, setPaintMode] = useState('random'); // 清空触发标记:每次递增就会触发所有网格重置颜色 const [clearFlag, setClearFlag] = useState(0); const handleClick = () => { let newGridSize = prompt("请输入16到100之间的数字"); if (newGridSize !== null) { newGridSize = parseInt(newGridSize); if (newGridSize < 16 || newGridSize > 100 || Number.isNaN(newGridSize)) { alert("输入错误,请输入16到100之间的数字"); } else { setGridSize(newGridSize); } } }; const paintBlack = () => setPaintMode('black'); const paintColor = () => setPaintMode('random'); const clearGrid = () => setClearFlag(prev => prev + 1); return ( <div className="wrapper"> <Buttons paintBlack={paintBlack} paintColor={paintColor} clearGrid={clearGrid} handleClick={handleClick} /> <div className="container"> <Grid gridSize={gridSize} paintMode={paintMode} clearFlag={clearFlag} /> </div> </div> ); } export default Board;
2. Grid 组件
import { useEffect, useRef } from "react"; import Square from "./Square"; function Grid({ gridSize, paintMode, clearFlag }) { const boardRef = useRef(null); useEffect(() => { boardRef.current.style.setProperty("--grid-size", gridSize); }, [gridSize]); const createSquares = () => { let div = []; for (let i = 0; i < gridSize * gridSize; i++) { // 把涂色模式、清空标记传递给每个网格组件 div.push(<Square key={i} paintMode={paintMode} clearFlag={clearFlag} />); } return div; }; return ( <div className="wrapper"> <div className="container"> <div ref={boardRef} className="board"> {createSquares()} </div> </div> </div> ); } export default Grid;
3. Buttons 组件
function Buttons({ handleClick, paintBlack, paintColor, clearGrid }) { return ( <div className="buttons"> <button id="button" onClick={handleClick}> 重置网格尺寸 </button> <button id="button" onClick={paintBlack}> 黑色 </button> <button id="button" onClick={paintColor}> 随机颜色 </button> {/* 修复清空按钮的触发逻辑 */} <button id="button" onClick={clearGrid}> 清空画布 </button> </div> ); } export default Buttons;
4. Square 组件
import { useState, useEffect } from "react"; function Square({ paintMode, clearFlag }) { // 初始颜色设为白色 const [color, setColor] = useState('#fff'); const style = { backgroundColor: color }; // 监听清空标记,标记变化时把当前网格重置为白色 useEffect(() => { setColor('#fff'); }, [clearFlag]); return ( <div className="square" style={style} onMouseEnter={() => { // 根据当前涂色模式设置颜色 if (paintMode === 'black') { setColor('rgb(0,0,0)'); } else { const randomR = Math.floor(Math.random() * 256); const randomG = Math.floor(Math.random() * 256); const randomB = Math.floor(Math.random() * 256); setColor(`rgb(${randomR}, ${randomG}, ${randomB})`); } }} ></div> ); } export default Square;
内容的提问来源于stack exchange,提问作者Miroslav B
相关产品推荐
相关产品推荐

