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

相关推荐
幼儿园技术家33 分钟前
多方案统一认证体系对比
前端
十一.36638 分钟前
83-84 包装类,字符串的方法
前端·javascript·vue.js
over6971 小时前
深入解析:基于 Vue 3 与 DeepSeek API 构建流式大模型聊天应用的完整实现
前端·javascript·面试
用户4099322502121 小时前
Vue3计算属性如何通过缓存特性优化表单验证与数据过滤?
前端·ai编程·trae
接着奏乐接着舞1 小时前
react useMeno useCallback
前端·javascript·react.js
码农阿豪1 小时前
Vue项目构建中ESLint的“换行符战争”:从报错到优雅解决
前端·javascript·vue.js
xhxxx2 小时前
AI打字机的秘密:一个 buffer 如何让机器学会“慢慢说话”
前端·vue.js·openai
韩曙亮2 小时前
【Web APIs】BOM 浏览器对象模型 ⑥ ( location 对象 | location 常用属性和方法 | URL 简介 )
前端·javascript·dom·url·bom·location·浏览器对象模型
用户21411832636022 小时前
CC-Switch配置切换神器:5秒搞定多设备同步,坚果云让配置永不丢失
前端
勤奋的懒洋洋3502 小时前
前端实现多个图片打包下载
前端