我正在尝试制作 Wordle 克隆 如何在触发更改后专注于下一个输入字段(用户输入单词后)
import {useRef} from 'react';
const Mainarea = () => {
// will use useState later in this
const boxes = [{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 : ""}];
var value = ""
const inputRef = useRef("");
return (
<div className="Mainarea">
<div className="mainBoxArea">
// This is the map function in question
{boxes.map(box => {
value = value + box.userInput;
return(
<div className="div" key = {box.id}>
<input ref = {inputRef} className = "boxview" maxLength={1} type="text"/>
</div>
)})}
</div>
</div>
);
}
export default Mainarea;
----------
用户添加单词后,我希望自动专注于下一个字段,因为此地图功能将触发 5 次
首先,你有一个inputs
数组,所以你需要一个refs
数组,在handleChange
函数上,你可以通过将索引递增 1 并在该索引上的目标input
上使用focus
事件来进入下一个input
。
import { useRef, useEffect } from "react";
const Mainarea = () => {
// will use useState later in this
const boxes = [
{ 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: "" }
];
var value = "";
const inputRefs = useRef([]);
useEffect(() => {
inputRefs.current = inputRefs.current.slice(0, boxes.length);
}, []);
const handleChange = (i) => {
if (i === boxes.length - 1) {
return;
}
inputRefs.current[i + 1].focus();
};
return (
<div className="Mainarea">
<div className="mainBoxArea">
{boxes.map((box, i) => {
value = value + box.userInput;
return (
<div className="div" key={box.id}>
<input
ref={(el) => (inputRefs.current[i] = el)}
className="boxview"
maxLength={1}
type="text"
onChange={() => handleChange(i)}
/>
</div>
);
})}
</div>
</div>
);
};
export default Mainarea;
这是工作代码沙箱示例