如何实现带输入隐藏功能的react-native-otp-inputs?
实现带输入隐藏功能的react-native-otp-inputs
步骤1:安装依赖
确保项目中已安装所需依赖,执行以下命令:
npm install react-native-otp-inputs react-native-keyboard-aware-scroll-view --save # 或使用yarn yarn add react-native-otp-inputs react-native-keyboard-aware-scroll-view
步骤2:基础实现(默认隐藏输入)
通过secureTextEntry属性开启输入隐藏,验证码会以圆点形式显示。以下是完整组件示例:
import React, { useState } from 'react'; import { View, StyleSheet } from 'react-native'; import OTPInputs from 'react-native-otp-inputs'; const OTPScreen = () => { const [otpCode, setOtpCode] = useState(''); // 处理验证码输入变化 const handleOtpChange = (value) => { setOtpCode(value); // 可在此添加验证码输入完成后的验证逻辑 }; return ( <View style={styles.container}> <OTPInputs value={otpCode} onChange={handleOtpChange} pinCount={6} // 设置验证码位数,可根据需求调整 secureTextEntry={true} // 核心:开启输入隐藏 style={styles.otpWrapper} textInputStyle={styles.otpInput} /> </View> ); }; const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', paddingHorizontal: 20, }, otpWrapper: { flexDirection: 'row', gap: 12, }, otpInput: { width: 50, height: 50, borderWidth: 1, borderColor: '#e0e0e0', borderRadius: 8, textAlign: 'center', fontSize: 20, backgroundColor: '#f8f8f8', }, }); export default OTPScreen;
步骤3:添加显示/隐藏切换功能(可选)
如果需要让用户手动切换验证码的显示状态,可以通过状态变量控制secureTextEntry的值:
import React, { useState } from 'react'; import { View, StyleSheet, TouchableOpacity, Text } from 'react-native'; import OTPInputs from 'react-native-otp-inputs'; const OTPScreen = () => { const [otpCode, setOtpCode] = useState(''); const [showOtp, setShowOtp] = useState(false); // 控制显示/隐藏的状态 const handleOtpChange = (value) => { setOtpCode(value); }; return ( <View style={styles.container}> <OTPInputs value={otpCode} onChange={handleOtpChange} pinCount={6} secureTextEntry={!showOtp} // 根据状态切换隐藏/显示 style={styles.otpWrapper} textInputStyle={styles.otpInput} /> {/* 切换按钮 */} <TouchableOpacity style={styles.toggleBtn} onPress={() => setShowOtp(!showOtp)} > <Text style={styles.toggleText}> {showOtp ? '隐藏验证码' : '显示验证码'} </Text> </TouchableOpacity> </View> ); }; const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', paddingHorizontal: 20, }, otpWrapper: { flexDirection: 'row', gap: 12, marginBottom: 20, }, otpInput: { width: 50, height: 50, borderWidth: 1, borderColor: '#e0e0e0', borderRadius: 8, textAlign: 'center', fontSize: 20, backgroundColor: '#f8f8f8', }, toggleBtn: { paddingVertical: 8, paddingHorizontal: 16, }, toggleText: { color: '#165DFF', fontSize: 16, }, }); export default OTPScreen;
内容的提问来源于stack exchange,提问作者M Fajar Firmansyah
相关产品推荐
相关产品推荐

