自定义验证码输入框,支持传入多个数量,如4位或者6位验证码,只需设置count
import { useRef } from "react";
import { Input } from "antd";
import styles from "./index.module.less";
interface OTPButtonProps {
count?: number;
onChange?: (value: string) => void;
}
const OTPButton = (props: OTPButtonProps) => {
const { count = 6, onChange } = props;
const inputArr = new Array(count).fill("");
const inputRefs = useRef<any>([]);
const getRef = (dom: any) => {
if (inputRefs?.current?.length === count) {
return;
}
inputRefs?.current?.push(dom);
};
const onKeyDown = (e: any, index: number) => {
// 按删除键
if (e?.key === "Backspace") {
if (!e.target.value && index > 0) {
const currentInputRef = inputRefs?.current[index];
currentInputRef.input.value = "";
const preInput = inputRefs.current[index - 1];
preInput?.select();
e.preventDefault();
}
}
};
const onValueChange = (
e: React.ChangeEvent<HTMLInputElement>,
index: number
) => {
let code = "";
inputRefs?.current?.forEach((ref: any) => {
const val = ref?.input?.value;
if (val) {
code += val;
}
});
const currentValue = e?.target?.value;
// currentValue有值,代表是输入
if (currentValue && index < count - 1) {
const nextInput = inputRefs.current[index + 1];
nextInput?.focus();
}
if (!currentValue && index > 0) {
const nextInput = inputRefs.current[index - 1];
nextInput?.select();
}
onChange?.(code);
};
return (
<div className={styles.codeInput}>
{inputArr.map((_, index) => {
return (
<Input
ref={getRef}
key={index}
className={styles.input}
maxLength={1}
onChange={(e) => onValueChange(e, index)}
onKeyDown={(e) => onKeyDown(e, index)}
/>
);
})}
</div>
);
};
export default OTPButton;
less 样式
.codeInput {
display: flex;
justify-content: center;
column-gap: 10px;
margin-top: 24px;
.input {
width: 36px;
height: 60px;
font-size: 20px;
}
:global {
.ant-input:focus,
.ant-input-focused {
border-color: #d4dde6;
box-shadow: none;
}
.ant-input:hover {
border-color: #d4dde6;
}
.ant-input {
border-color: #d4dde6;
}
}
}