React Native 输入验证码

image.png

import React, {useImperativeHandle, useRef, useState} from 'react';
import {
TextInput,
View,
StyleSheet,
TouchableOpacity,
ViewProps,
} from 'react-native';
import {Size} from '../../../core/screenTools';
import theme from '../../theme';
import {observer} from 'mobx-react-lite';

const codeSize = 4;

interface VerifyCodeInputProps extends ViewProps {
onAllFilled?: (codesStr: string) => void;
}

interface VerifyCodeInputRef {
clear: () => void;
}

interface Code {
value: string;
}

const getDefaultCodes = () => {
const codes: Code[] = [];
for (let i = 0; i < codeSize; i++) {
codes.push({value: ''});
}
return codes;
};

const VerifyCodeInput = observer(
(props, ref) => {
const inputs = useRef([]);
const [codes, setCodes] = useState(getDefaultCodes());
const checkText = (text: string) => {
const re = new RegExp('\d');
if (re.test(text)) {
return text;
}
return '';
};
const clearAll = () => {
inputs.current.map((item) => {
item.clear();
});
setCodes(getDefaultCodes());
};
const clear = (index: number) => {
const codesClone = [...codes];
codesClone[index].value = '';
setCodes(codesClone);
inputs.current[index].clear();
};
//粘贴
const handlePaste = (text: string, index: number) => {
//格式化text
text = checkText(text);
text = text.slice(0, codeSize - index);
//给text赋值
const codesClone = [...codes];
for (let i = 0; i < text.length; i++) {
codesClone[index + i].value = text[i];
}
setCodes(codesClone);
if (text.length > 0) {
//获取下一个需要获取焦点的input
const textInput = inputs.current[index + text.length];
//如果存在则获取焦点
if (textInput) {
textInput.focus();
}
//否则当前input为最后一个,取消当前input焦点 并 清空数据
else {
inputs.current[index].blur();
props.onAllFilled &&
props.onAllFilled(
codes.reduce(
(previousValue, currentValue) =>
previousValue + currentValue.value,
''
)
);
}
}
};
//正常输入
const handleEdit = (text: string, index: number) => {
//格式化text
text = checkText(text);
//给text赋值
const codesClone = [...codes];
codesClone[index].value = text;
setCodes(codesClone);
//是合法字符才切换input
if (text) {
//获取下一个需要获取焦点的input
const textInput = inputs.current[index + 1];
//如果存在则获取焦点
if (textInput) {
textInput.focus();
}
//否则当前input为最后一个,取消当前input焦点 并 清空数据
else {
inputs.current[index].blur();
props.onAllFilled &&
props.onAllFilled(
codes.reduce(
(previousValue, currentValue) =>
previousValue + currentValue.value,
''
)
);
}
}
};
useImperativeHandle(ref, () => {
return {
clear: () => clearAll(),
};
});
const renderTextInput = (code: Code, index: number) => {
return (
key={index}
ref={(ref) => {
if (ref) {
inputs.current[index] = ref;
}
}}
style={styles.input}
caretHidden={true}
contextMenuHidden={true}
keyboardType={'number-pad'}
autoFocus={index === 0}
value={code.value}
onChangeText={(text) => {
//粘贴操作
if (text.length > 1) {
handlePaste(text, index);
}
//正常输入
else {
handleEdit(text, index);
}
}}
onKeyPress={(event) => {
//点击键盘删除按钮,回退到上一个 textInput 并且清空当前 textInput 数据
if (event.nativeEvent.key === 'Backspace') {
const textInput = inputs.current[index - 1];
if (textInput) {
clear(index - 1);
textInput.focus();
}
}
}}
/>
);
};
return (

{codes.map((item, index) => {
return renderTextInput(item, index);
})}
onPress={() => {
//判断当前需要填充数据的第一个input
const firstEmptyIndex = codes.findIndex((item, index) => {
return !item.value;
});
if (firstEmptyIndex !== -1) {
inputs.current[firstEmptyIndex].focus();
}
}}
style={styles.cover_btn}
/>

);
},
{forwardRef: true}
);

const styles = StyleSheet.create({
container: {flexDirection: 'row', justifyContent: 'space-between'},
input: {
width: Size(30),
textAlign: 'center',
borderBottomWidth: 2,
borderColor: theme.borderColorPrimary,
},
cover_btn: {position: 'absolute', left: 0, top: 0, right: 0, bottom: 0},
});

export default VerifyCodeInput;

你可能感兴趣的:(React Native 输入验证码)