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

相关推荐
bin91531 小时前
DeepSeek 助力 Vue 开发:打造丝滑的复制到剪贴板(Copy to Clipboard)
前端·javascript·vue.js·ecmascript·deepseek
晴空万里藏片云3 小时前
elment Table多级表头固定列后,合计行错位显示问题解决
前端·javascript·vue.js
曦月合一3 小时前
html中iframe标签 隐藏滚动条
前端·html·iframe
奶球不是球3 小时前
el-button按钮的loading状态设置
前端·javascript
kidding7233 小时前
前端VUE3的面试题
前端·typescript·compositionapi·fragment·teleport·suspense
Σίσυφος19005 小时前
halcon 条形码、二维码识别、opencv识别
前端·数据库
学代码的小前端5 小时前
0基础学前端-----CSS DAY13
前端·css
css趣多多6 小时前
案例自定义tabBar
前端
姑苏洛言7 小时前
DeepSeek写微信转盘小程序需求文档,这不比产品经理强?
前端
林的快手7 小时前
CSS列表属性
前端·javascript·css·ajax·firefox·html5·safari