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

相关推荐
Jackson__24 分钟前
聊聊 JS 中的可选链 ?.
前端
前端小崔29 分钟前
前端面试题之ES6保姆级教程
开发语言·前端·javascript·面试·职场和发展·ecmascript·es6
Bug从此不上门39 分钟前
【无标题】
前端·javascript·uni-app·vue
HarderCoder39 分钟前
ByAI:Redux中间件的原理和ts简化实现
前端·redux
贩卖纯净水.42 分钟前
Webpack依赖
前端·webpack·node.js
crary,记忆43 分钟前
微前端 - Module Federation使用完整示例
前端·react·angular
不知几秋1 小时前
Spring Boot
java·前端·spring boot
程序猿ZhangSir1 小时前
Vue3 项目的基本架构解读
前端·javascript·vue.js
HarderCoder1 小时前
ByAI: Redux的typescript简化实现
前端
90后的晨仔1 小时前
RxSwift 框架解析
前端·ios