ReactNative支付密码输入框实现详解

正文

项目中需求如果涉及钱包,支付等功能,可以大概率会用到输入密码组件,也算是个常见组件吧。

之前写过一个纯js的开源组件,使用的类的形式,也比较老了,可直接添加npm库到项目中进行使用。

hooks版本

最近项目需要,又重新写了一个hooks版本的,现在直接上源码,对于不想添加依赖库的伙伴,可直接复制源码到项目中,直接使用。

'use strict';
import React, {useRef, useState} from 'react';
import {StyleSheet, View, Pressable, TextInput} from 'react-native';
// 支付密码输入框
const PasswordInput = ({isAutoFocus = false}) => {
 const [msg, setMsg] = useState('');
 const textInputRef = useRef();
 const onEnd = (text: string) => {
 console.log('输入密码:', text);
 };
 const _getInputItem = () => {
 let inputItem = [];
 for (let i = 0; i < 6; i++) {
 inputItem.push(
 <View key={i} style={i === 5 ? [styles.textInputView, {borderRightWidth: 1}] : [styles.textInputView, {borderRightWidth: 0}]}>
 {i < msg.length ? <View style={{width: 16, height: 16, backgroundColor: '#222', borderRadius: 8}} /> : null}
 </View>,
 );
 }
 return inputItem;
 };
 const _onPress = () => {
 textInputRef?.current.focus();
 };
 return (
 <Pressable onPress={_onPress}>
 <View style={styles.container}>
 <View style={{flexDirection: 'row', marginTop: 36, justifyContent: 'center'}}>
 <TextInput
 style={styles.textInputMsg}
 ref={textInputRef}
 maxLength={6}
 autoFocus={isAutoFocus}
 keyboardType="number-pad"
 defaultValue={msg}
 onChangeText={text => {
 setMsg(text);
 if (text.length === 6) {
 onEnd(text);
 }
 }}
 />
 {_getInputItem()}
 </View>
 </View>
 </Pressable>
 );
};
const styles = StyleSheet.create({
 container: {
 flex: 1,
 backgroundColor: '#ffffff',
 justifyContent: 'center',
 alignItems: 'center',
 },
 textInputView: {
 height: 85 / 2,
 width: 85 / 2,
 borderWidth: 1,
 borderColor: '#c9c7c7',
 justifyContent: 'center',
 alignItems: 'center',
 },
 textInputMsg: {
 height: 45,
 zIndex: 99,
 position: 'absolute',
 width: 45 * 6,
 opacity: 0,
 },
});
export default PasswordInput;

使用方式就很简单了:

<PasswordInput />

项目库地址链接Github: github.com/wayne214/re…

作者:wayne214

%s 个评论

要回复文章请先登录注册