求助:React中实现5x5随机字母网格,输入有值时替换两个单元格
解决方案
你可以通过修改generateGrid函数,让它支持传入自定义字母,并在有值时随机替换两个不同单元格的内容,同时在组件中监听输入框的变化来重新生成网格。以下是完整的修改代码:
import { useState, useEffect } from 'react'; const alphabet = "abcdefghijklmnopqrstuvwxyz"; const getRandomLetterRow = (size) => Array.from({ length: size }, () => { return alphabet[Math.floor(Math.random() * alphabet.length)]; }); const generateGrid = (size = 5, customLetter = null) => { // 先生成全随机的基础网格 const grid = Array.from({ length: size }, () => getRandomLetterRow(size)); // 当存在有效的自定义字母时,替换两个随机位置的单元格 if (customLetter && customLetter.trim().length === 1) { const usedPositions = new Set(); const targetLetter = customLetter.trim().toLowerCase(); // 生成两个不重复的随机坐标 while (usedPositions.size < 2) { const row = Math.floor(Math.random() * size); const col = Math.floor(Math.random() * size); const positionKey = `${row}-${col}`; if (!usedPositions.has(positionKey)) { usedPositions.add(positionKey); grid[row][col] = targetLetter; } } } return grid; }; function App(){ const [customLetter, setCustomLetter] = useState(''); const [grid, setGrid] = useState(generateGrid()); // 监听自定义字母变化,重新生成网格 useEffect(() => { setGrid(generateGrid(5, customLetter)); }, [customLetter]); // 渲染网格的辅助函数 const renderGrid = () => { return grid.map((row, rowIndex) => ( <div key={rowIndex} style={{ display: 'flex', marginBottom: '4px' }}> {row.map((letter, colIndex) => ( <div key={`${rowIndex}-${colIndex}`} style={{ width: '40px', height: '40px', border: '1px solid #ddd', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '18px', marginRight: '4px' }} > {letter} </div> ))} </div> )); }; return( <div style={{ padding: '20px' }}> <input type="text" placeholder="输入单个字母" onChange={(e) => setCustomLetter(e.target.value)} maxLength={1} // 限制仅能输入一个字符 style={{ padding: '8px', fontSize: '16px' }} /> <div style={{ marginTop: '20px' }}> {renderGrid()} </div> </div> ) } export default App;
关键修改说明
- 增强
generateGrid函数:新增customLetter参数,先生成全随机网格,再通过循环生成两个不重复的随机坐标,替换对应位置的字符为自定义字母。使用Set确保两个位置不重复,避免覆盖同一个单元格。 - 输入框限制:添加
maxLength={1}防止输入多个字符,同时在处理时使用trim()和toLowerCase(),保证输入的字母和字母表格式统一。 - 监听输入变化:使用
useEffect监听customLetter的变化,每次输入改变时重新生成网格,确保界面实时更新。 - 网格渲染:新增
renderGrid函数将二维数组转换为可视化的网格布局,方便查看效果。
内容的提问来源于stack exchange,提问作者Alien18
相关产品推荐
相关产品推荐

