import { Divider, Input } from 'antd' import React, { FC, Fragment, useRef } from 'react' import './style.less' interface VerifyCodeInputProps extends React.HTMLAttributes { verifyCode: string[] setVerifyCode: (code: string[]) => void length?: number onEnter?: Function } export const VerifyCodeInput: FC = ({ verifyCode, setVerifyCode, length = 6, onEnter, }) => { const inputRef = useRef([]) const handleChange = (val: string | undefined = '', index: number) => { const num = parseInt(val) if (isNaN(num)) { val = '' } else { val = String(num) } const codes = [...verifyCode] codes[index] = val.split('').slice(-1)[0] || '' setVerifyCode(codes) if (val && inputRef.current[index + 1]) { inputRef.current[index + 1].focus() } } const handleKeyDown = (evt: any, index: number) => { const currentVal = verifyCode[index] switch (evt.keyCode) { case 8: if (!currentVal && inputRef.current[index - 1]) { handleChange('', index - 1) inputRef.current[index - 1].focus() } break case 13: onEnter?.() break default: break } } return (
{new Array(length).fill(0).map((_, index) => ( (inputRef.current[index] = el)} className="approw-code-input-item" size="large" autoFocus={index === 0} onKeyDown={(evt) => handleKeyDown(evt, index)} value={verifyCode[index]} onChange={(evt) => handleChange(evt.target.value, index)} /> {index === Math.floor(length / 2 - 1) && ( )} ))}
) }