前端-自定义验证码输入框(OTP)

自定义验证码输入框,支持传入多个数量,如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;
    }
  }
}

  • 10
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值