-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathVerifyCodeInput.js
92 lines (84 loc) · 2.72 KB
/
VerifyCodeInput.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import React, { PureComponent } from 'react';
import {
Text,
TextInput,
TouchableOpacity,
View
} from 'react-native';
import lodash from 'lodash';
import PropTypes from 'prop-types';
import styles from './VerifyCode.style';
const propTypes = {
onChangeText: PropTypes.func.isRequired, // 验证码实时变化值
verifyCodeLength: PropTypes.number.isRequired, // 验证码数
};
const defaultProps = {
onChangeText: () => {},
verifyCodeLength: 6, // 默认6位
};
// 验证码组件
class VerifyCode extends PureComponent {
constructor(props) {
super(props);
this.state = {
verifyCode: '', // 验证码
};
this.onTouchInput = this.onTouchInput.bind(this);
}
onTouchInput() {
const isFocused = this.textInput.isFocused();
if (!isFocused) {
this.textInput.focus();
}
}
renderVerifyCode(value) {
const { verifyCodeLength } = this.props;
const paddedValue = lodash.padEnd(value, verifyCodeLength, ' ');
const valueArray = paddedValue.split('');
return (
<TouchableOpacity
activeOpacity={1}
onPress={this.onTouchInput}
style={styles.verifyTextContainer}
>
{valueArray.map((digit, index) => (
<View
key={index}
style={digit === ' ' ? styles.textInputItem : styles.textInputItemIn}
>
<Text style={styles.verifyText}>{digit}</Text>
</View>
))}
</TouchableOpacity>
);
}
render() {
const { verifyCode } = this.state;
const { onChangeText, verifyCodeLength } = this.props;
return (
<View style={styles.verifyContainer}>
{this.renderVerifyCode(verifyCode)}
<TextInput
ref={(ref) => { this.textInput = ref; }}
underlineColorAndroid="transparent"
caretHidden
style={styles.textInput}
autoFocus={true}
keyboardType={'numeric'}
maxLength={verifyCodeLength}
onChangeText={(text) => {
const reg = /^[0-9]*$/;
if (reg.test(text)) {
this.setState({ verifyCode: text });
onChangeText(text);
}
}}
value={verifyCode}
/>
</View>
);
}
}
VerifyCode.propTypes = propTypes;
VerifyCode.defaultProps = defaultProps;
export default VerifyCode;