我在 React 中做了 OTP 輸入你可以看到這個影像。一行是一個輸入,我有 6 個輸入。輸入作業沒有問題。我需要當組件打開時,第一個輸入必須是自動對焦。當我使用<input autofocus/>最后一個輸入是自動對焦時,我需要第一個輸入。
我的父組件
const [code, setcode] = useState(new Array(6).fill(""));
一次性密碼組件
<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();
}
};
uj5u.com熱心網友回復:
如果您只想在組件掛載時獲得焦點,則可以使用陣列的索引。只需添加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
/>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/480975.html
標籤:javascript 数组 反应
上一篇:執行代碼時隱藏和取消隱藏或<form>(進度條ao)
下一篇:Vue在腳本中使用js來參考元素
