我的项目中需要如果波及钱包,领取等性能,能够大概率会用到输出明码组件,也算是个常见组件吧。
之前写过一个纯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 />
我的项目库地址链接Github:
https://github.com/wayne214/r...