阅读 63

ReactNative支付密码输入框

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

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

最近项目需要,又重新写了一个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 />


作者:wayne214
链接:https://juejin.cn/post/7170513204731183117


文章分类
代码人生
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐