javascript - 如何在退格键按下时删除 OTP 用户输入
问题描述
我编写了一个 OTP 组件,但它有两个我无法解决的问题。
第一个问题是,当我按退格键时,我想删除输入值,然后转到上一个输入字段将其删除。
第二个问题是,当我删除一个输入(即第三个框)时,我的代码让我专注于下一个输入字段。
如何正确实现退格键按下并在删除输入时转到上一个输入字段?
这是我到目前为止所做的:
import React, { useState } from "react";
import css from '../components/css/OTP.css'
const Axios = require('axios')
const OTP = () => {
const [otp, setOtp] = useState(new Array(4).fill(""));
const handleChange = (element, index) => {
if (isNaN(element.value)) return false;
setOtp([...otp.map((d, idx) => (idx === index ? element.value : d))]);
//Focus next input
if (element.nextSibling) {
element.nextSibling.focus();
}
}
//eğer girilen OTP backendden gelen OTP ile aynıysa matchleştiğini göster ve kullanıcıyı verifike et daha sonra dashboarda aktar.
const checkOTP = async () =>{
try
{
const url = "http://localhost:5000/auth/otp"
const response = await Axios.post(url , {otp} , {withCredentials: true})
if(response.status!==200){
alert("Invalid OTP entry")
}
else{
alert("OTP successful!")
}
}
catch(err)
{
console.log(err)
}
}
return (
<>
<div className="otp-window">
<div className="otp-modal">
<div className="row">
<div className="info">
<p className="otp-info">Please enter the OTP sent to your email</p>
{otp.map((data, index) => {
return (
<input
className="otp-field"
type="text"
name="otp"
maxLength="1"
key={index}
value={data}
onChange={e => handleChange(e.target, index)}
onFocus={e => e.target.select()}
/>
);
})}
<p className="otp-entered">OTP : {otp.join("")}</p>
<p>
<button
className="clear-button"
onClick={e => setOtp([...otp.map(v => "")])}
>
Clear
</button>
<button
className="verify-button"
onClick={e =>
alert("Entered OTP is " + otp.join(""))
}
onClick={checkOTP}>
Verify OTP
</button>
</p>
</div>
</div>
</div>
</div>
</>
);
};
export default OTP;
解决方案
您可以使用input
事件并像这样检查对象的event.inputType
属性。event
您可能必须将onChange
道具更改为onInput
。
if (event.inputType === 'deleteContentBackward' && event.target.value === '') {
// Focus on the previous field
}
推荐阅读
- c# - MongoDB 使用嵌套对象属性之一的条件更新嵌套对象
- mysql - 为什么我得到错误的烧瓶计数输出格式?
- javascript - fabric.js:在用户绘图时填充自由绘图路径(套索工具)
- apache-spark - 如何将 Spark 数据框与 Databricks Deltalake 上的配置单元表合并?
- python - Python“AttributeError:'NoneType'对象没有属性”错误
- node.js - 护照身份验证不适用于使用 Jwt 的 Nodejs 登录
- python - 在 Plotly 中创建 3D 曲面图
- c++ - 如何静态链接除 cygwin1.dll 之外的每个 .dll?
- swift - Firebase 存储/Google Places - 异步 - 等待支持
- javascript - onclick 功能不起作用,因为它不在主 retun 语句中