React 中 OTP 输入字段的第一个输入自动对焦
First input autofocus for OTP input fields in React
我在 React 中输入了 OTP You can see this image。一根线是一个输入,我有 6 个输入。输入工作不是问题。我需要在组件打开时,第一个输入必须是自动对焦。当我使用 <input autofocus/>
最后一个输入是自动对焦时,我需要第一个输入。
我的父组件
const [code, setcode] = useState(new Array(6).fill(""));
OTP 组件
<div className="digit-inputs">
{props.code.map((data, index) => {
return (
<input
disabled={props.second <= 0 ? true : false}
type="text"
className="otp-field"
name="otp"
maxLength={1}
key={index}
style={data ? { borderBottom: "3px solid #7dbf2a" } : { borderBottom: "3px solid grey" }}
value={data}
onChange={(e) => handleChange(e.target, index)}
onFocus={(e) => e.target.select}
/>
);
})}
</div>
我的函数
const handleChange = (element, index) => {
if (isNaN(element.value)) return false;
props.setcode([...props.code.map((d, indx) => (indx === index ? element.value : d))]);
//Focus next input
if (element.nextSibling) {
element.nextSibling.focus();
}
};
如果只想在组件挂载时获得焦点,可以使用数组的索引。只需添加 autoFocus={index === 0}
.
<input
type="text"
className="otp-field"
name="otp"
maxLength={1}
key={index}
style={
data
? { borderBottom: "3px solid #7dbf2a" }
: { borderBottom: "3px solid grey" }
}
//value={data}
onFocus={(e) => e.target.select}
autoFocus={index === 0} // add this line
//onChange
/>
我在 React 中输入了 OTP You can see this image。一根线是一个输入,我有 6 个输入。输入工作不是问题。我需要在组件打开时,第一个输入必须是自动对焦。当我使用 <input autofocus/>
最后一个输入是自动对焦时,我需要第一个输入。
我的父组件
const [code, setcode] = useState(new Array(6).fill(""));
OTP 组件
<div className="digit-inputs">
{props.code.map((data, index) => {
return (
<input
disabled={props.second <= 0 ? true : false}
type="text"
className="otp-field"
name="otp"
maxLength={1}
key={index}
style={data ? { borderBottom: "3px solid #7dbf2a" } : { borderBottom: "3px solid grey" }}
value={data}
onChange={(e) => handleChange(e.target, index)}
onFocus={(e) => e.target.select}
/>
);
})}
</div>
我的函数
const handleChange = (element, index) => {
if (isNaN(element.value)) return false;
props.setcode([...props.code.map((d, indx) => (indx === index ? element.value : d))]);
//Focus next input
if (element.nextSibling) {
element.nextSibling.focus();
}
};
如果只想在组件挂载时获得焦点,可以使用数组的索引。只需添加 autoFocus={index === 0}
.
<input
type="text"
className="otp-field"
name="otp"
maxLength={1}
key={index}
style={
data
? { borderBottom: "3px solid #7dbf2a" }
: { borderBottom: "3px solid grey" }
}
//value={data}
onFocus={(e) => e.target.select}
autoFocus={index === 0} // add this line
//onChange
/>