React中使用map渲染输入框时,如何自动聚焦到下一个输入框?
Wordle克隆:输入后自动聚焦下一个输入框的实现方案
你的问题出在单个useRef无法区分多个输入框——map循环生成的5个input都绑定了同一个inputRef,自然没法精准定位到下一个输入框。下面是具体的修复方案:
核心修改点
- 用
useRef创建一个数组,存储每个输入框的DOM引用 - 给每个输入框添加
onChange事件,处理输入值更新+自动聚焦逻辑 - 用
useState管理输入框的状态(你提到之后会用,这里直接整合进去)
修改后的完整代码
import { useRef, useState } from 'react'; const Mainarea = () => { // 用useState管理输入框状态 const [boxes, setBoxes] = useState([ { color: "white", id: 1, userInput: "" }, { color: "white", id: 2, userInput: "" }, { color: "white", id: 3, userInput: "" }, { color: "white", id: 4, userInput: "" }, { color: "white", id: 5, userInput: "" } ]); // 创建ref数组,存储每个输入框的DOM引用 const inputRefs = useRef([]); // 处理输入变化的函数 const handleInputChange = (e, boxId) => { const inputValue = e.target.value.toUpperCase(); // 统一转大写,贴合Wordle交互 // 更新对应输入框的状态 setBoxes(prevBoxes => prevBoxes.map(box => box.id === boxId ? { ...box, userInput: inputValue } : box )); // 如果输入了内容,且不是最后一个输入框,聚焦下一个 if (inputValue && boxId < boxes.length) { inputRefs.current[boxId].focus(); } }; return ( <div className="Mainarea"> <div className="mainBoxArea"> {boxes.map(box => { return ( <div className="div" key={box.id}> <input // 给每个输入框绑定对应的ref ref={el => inputRefs.current[box.id - 1] = el} className="boxview" maxLength={1} type="text" value={box.userInput} onChange={(e) => handleInputChange(e, box.id)} /> </div> ) })} </div> </div> ); } export default Mainarea;
关键逻辑说明
- Ref数组的使用:
inputRefs.current是一个数组,每个元素对应一个输入框的DOM节点,通过box.id - 1对应到正确的数组索引(因为id从1开始,数组索引从0开始)。 - 输入处理:
handleInputChange先更新对应输入框的状态,然后判断如果有输入内容,且当前不是最后一个输入框,就调用下一个输入框的focus()方法。 - 大写转换:添加了
toUpperCase(),让输入自动转为大写,更贴合Wordle的交互逻辑。
内容的提问来源于stack exchange,提问作者Aryan Kaushik
相关产品推荐
相关产品推荐

