使用原生RN写一个输入验证码的选项(四个输入框)

js 复制代码
import * as React from 'react';
import {View, TextInput, SafeAreaView} from 'react-native';

const VerificationCodeInput = () => {
  const inputRefs = [
    React.useRef(),
    React.useRef(),
    React.useRef(),
    React.useRef(),
  ];

  const handleInputChange = (index, text) => {
    if (text.trim() === '' || /^\d+$/.test(text)) {
      if (text.trim() === '') {
        // 清空当前输入框并将焦点切换到前一个输入框
        inputRefs[index].current.clear();
        if (index > 0) {
          inputRefs[index - 1].current.focus();
        }
      } else {
        // 更新当前输入框的值并将焦点切换到下一个输入框
        inputRefs[index].current.setNativeProps({text: text[text.length - 1]});
        if (index < inputRefs.length - 1) {
          inputRefs[index + 1].current.focus();
        }
      }
    }
  };

  const handlePaste = e => {
    const pastedText = e.nativeEvent.clipboardData.getData('text').trim();
    for (let i = 0; i < Math.min(pastedText.length, inputRefs.length); i++) {
      inputRefs[i].current.setNativeProps({text: pastedText[i]});
      if (i < inputRefs.length - 1) {
        inputRefs[i + 1].current.focus();
      }
    }
  };

  return (
    <SafeAreaView>
      <View style={{flexDirection: 'row'}}>
        {inputRefs.map((ref, index) => (
          <TextInput
            key={index}
            ref={inputRefs[index]}
            style={{
              borderWidth: 1,
              borderColor: '#000',
              borderRadius: 4,
              width: 50,
              height: 50,
              marginRight: 10,
              textAlign: 'center',
            }}
            underlineColorAndroid="transparent"
            underlineColor="transparent"
            underlineStyle={{backgroundColor: 'transparent'}}
            keyboardType="numeric"
            maxLength={1}
            onChangeText={text => handleInputChange(index, text)}
            onPaste={handlePaste}
          />
        ))}
      </View>
    </SafeAreaView>
  );
};

export default VerificationCodeInput;

上面这段代码目前效果有 1.输入一个数字后光标会跳转到下一个输入框,直到最后一个输入框 2.删除一个数字后,光标会继续向前删除(如果当前项为' ',光标不会有反应,一定是要有内容的删除) 3.暂时不能支持复制粘贴四位数字然后会自动排列到上面,这个需要插件或者别的东西获取权限,目前没做

相关推荐
ZC跨境爬虫几秒前
3D地球卫星轨道可视化平台开发Day2(轨道错位Bug修复+模块化结构优化)
前端·3d·html·json·bug
ZC跨境爬虫3 分钟前
3D 地球卫星轨道可视化平台开发 Day1(3D 场景、卫星渲染与筛选交互实现)
前端·3d·html·json·交互
研究点啥好呢9 分钟前
Github热榜项目推荐 | React生态系统的成熟演进
前端·react.js·github
daols8816 分钟前
vxe-table 自定义数字行主键,解决默认字符串主键与后端类型不匹配问题
前端·javascript·vue.js·vxe-table
skywalk816319 分钟前
g4f提供的模型调用:python JavaScript和curl
前端·javascript·vue.js·g4f
R-sz25 分钟前
前端直接将页面 HTML 报表导出为 Word 文档,html转word
前端·html·word
恋恋风尘hhh25 分钟前
Web 前端安全机制分析:以瑞数(RisShu)为例
前端·安全
freewlt42 分钟前
前端安全新范式:2026年防护实战
前端·安全
包子源43 分钟前
React-PDF 详解:API 要点与在线简历项目中的落地
前端·react.js·pdf
Bigger1 小时前
第九章:我是如何剖析 Claude Code 的 CLI 里的安全沙盒与指令拦截机制的
前端·claude·源码阅读