You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ReactJS实现验证码输入自动跳转、掩码及自动提交功能求助

解决Material UI验证码输入框的自动跳转、掩码及自动提交问题

针对你的需求,我们可以通过useRef管理输入框引用、结合状态存储真实验证码值来实现所有功能,以下是完整的实现方案:

核心实现思路

  • 用useRef数组获取每个输入框的DOM引用,解决聚焦失效问题
  • 用状态存储真实验证码内容,输入框仅显示*实现掩码效果
  • 监听输入和键盘事件,处理自动跳转、退格回退及最后一位输入后的自动提交

完整代码示例

import React, { useState, useRef } from 'react';
import { Grid, Input, Button } from '@mui/material';

const VerificationCode = () => {
  // 存储真实验证码的状态
  const [code, setCode] = useState(['', '', '', '']);
  // 存储四个输入框的引用
  const inputRefs = useRef([]);

  // 处理输入内容变化
  const handleChange = (index, e) => {
    const value = e.target.value.replace(/\D/g, ''); // 只允许数字输入
    if (value.length > 1) return; // 限制单个字符

    const newCode = [...code];
    newCode[index] = value;
    setCode(newCode);

    // 输入后自动跳转到下一个输入框
    if (value && index < 3) {
      inputRefs.current[index + 1].focus();
    }

    // 输入完最后一个字符自动提交
    if (index === 3 && value) {
      handleSubmit();
    }
  };

  // 处理键盘退格事件
  const handleKeyDown = (index, e) => {
    if (e.key === 'Backspace' && !code[index]) {
      // 当前输入框为空时,退格回到上一个输入框并清空
      if (index > 0) {
        const newCode = [...code];
        newCode[index - 1] = '';
        setCode(newCode);
        inputRefs.current[index - 1].focus();
      }
    }
  };

  // 表单提交逻辑
  const handleSubmit = () => {
    const fullCode = code.join('');
    console.log('提交验证码:', fullCode);
    // 这里替换成你的实际提交逻辑
    // 比如调用API、提交表单等
  };

  return (
    <Grid container spacing={2}>
      {[0, 1, 2, 3].map((index) => (
        <Grid item xs={3} key={index}>
          <Input
            disableUnderline
            inputProps={{ maxLength: 1, style: { textAlign: 'center' } }}
            type="text"
            name={`cod${index + 1}`}
            sx={{ width: 60, borderBottom: 1 }}
            ref={(el) => (inputRefs.current[index] = el)}
            value={code[index] ? '*' : ''}
            onChange={(e) => handleChange(index, e)}
            onKeyDown={(e) => handleKeyDown(index, e)}
          />
        </Grid>
      ))}
      {/* 可选:手动提交按钮 */}
      <Grid item xs={12}>
        <Button variant="contained" onClick={handleSubmit}>
          手动提交
        </Button>
      </Grid>
    </Grid>
  );
};

export default VerificationCode;

关键代码说明

  1. 输入框引用管理:通过useRef([])创建引用数组,在每个Input的ref属性中存入对应索引的DOM元素,确保能准确获取并聚焦目标输入框。
  2. 掩码实现:输入框的value绑定为code[index] ? '*' : '',用户输入的真实值存储在code状态中,既实现掩码效果又保留真实数据。
  3. 自动跳转逻辑:在handleChange中,当当前输入框有值且不是最后一个时,调用inputRefs.current[index + 1].focus()聚焦下一个输入框。
  4. 自动提交:当最后一个输入框(索引3)有输入时,直接触发handleSubmit函数。
  5. 退格回退:监听Backspace按键,若当前输入框为空则聚焦上一个输入框并清空对应值,提升用户体验。

内容的提问来源于stack exchange,提问作者Glo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 20:47:44