使用原生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.暂时不能支持复制粘贴四位数字然后会自动排列到上面,这个需要插件或者别的东西获取权限,目前没做

相关推荐
烛阴11 分钟前
UV Coordinates & Uniforms -- OpenGL UV坐标和Uniform变量
前端·webgl
姑苏洛言15 分钟前
扫码小程序实现仓库进销存管理中遇到的问题 setStorageSync 存储大小限制错误解决方案
前端·后端
烛阴26 分钟前
JavaScript 的 8 大“阴间陷阱”,你绝对踩过!99% 程序员崩溃瞬间
前端·javascript·面试
lh_12541 小时前
ECharts 地图开发入门
前端·javascript·echarts
jjw_zyfx1 小时前
成熟的前端vue vite websocket,Django后端实现方案包含主动断开websocket连接的实现
前端·vue.js·websocket
Mikey_n2 小时前
前台调用接口的方式及速率对比
前端
周之鸥2 小时前
使用 Electron 打包可执行文件和资源:完整实战教程
前端·javascript·electron
我爱吃朱肉2 小时前
HTMLCSS模板实现水滴动画效果
前端·css·css3
机器视觉知识推荐、就业指导2 小时前
开源QML控件:进度条滑动控件(含源码下载链接)
前端·qt·开源·qml
前端snow2 小时前
前端全栈第二课:用typeorm向数据库添加数据---一对多关系
前端·javascript