React Native密码输入框星号/明文切换显示异常问题求助
问题解决方法
你的问题根源在于手动替换了TextInput的value值,导致输入时实际存储的密码内容被干扰。正确的做法是用TextInput自带的secureTextEntry属性来控制密码显示/隐藏,而非自己生成星号替换value。
修改步骤:
- 删掉手动设置value为星号的代码,将value直接绑定真实密码状态
password - 启用
secureTextEntry={!showPassword}属性,用它控制是否显示星号
修改后的完整代码:
<LinearGradient colors={focused2?['#FF53C0', '#FF53C000', '#FF53C000']:['#60FFCA', '#60FFCA00', '#60FFCA00']} start={{x: 0.6, y: 0}} end={{x: 1, y: 0.8}} style={styles.PasswordLinearGradient}> <View style={styles.PasswordView}> <Image source={focused2?require('../assets/images/Password_Pink.png'):require('../assets/images/PasswordIcon.png')} style={styles.PasswordLogo}></Image> <TextInput placeholder="Password" ref={ref_input1} onFocus={handleFocus2} onBlur={handleBlur2} onChangeText={text=>setPassword(text)} secureTextEntry={!showPassword} value={password} placeholderTextColor={'rgba(200, 200, 200, 1)'} style={styles.EmailTextInput}></TextInput> {focused2==true? <TouchableOpacity onPress={()=>togglePassword()}> <Image source={!showPassword?require('../assets/images/Show_Password_Pink.png'):require('../assets/images/Hide_Password_Pink.png')} style={styles.HidePasswordLogo}></Image> </TouchableOpacity> : <TouchableOpacity onPress={()=>togglePassword()}> <Image source={!showPassword?require('../assets/images/Show_Password.png'):require('../assets/images/Hide_Password.png')} style={styles.HidePasswordLogo}></Image> </TouchableOpacity> } </View> </LinearGradient>
原因说明:
TextInput的secureTextEntry是官方提供的密码隐藏属性,它仅在界面上显示星号,但实际的value值始终是真实的密码内容。你之前手动替换value为星号,会导致输入时onChangeText拿到的是星号而非真实输入的字符,切换显示状态后自然看不到正确内容。改用官方属性后,既能实现显示/隐藏的交互效果,又能保证密码值的准确性。
内容的提问来源于stack exchange,提问作者Brijesh Bhikadiya
相关产品推荐
相关产品推荐

