You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native Paper密码输入框切换显示后输入内容丢失问题求助

解决密码输入框切换可见性后输入内容清空的问题

问题原因

切换secureTextEntry属性时,TextInput(此处为react-native-paper的实现)会重新初始化原生输入控件,导致原生层的输入状态丢失,即使使用受控组件绑定value,也可能出现内容不同步的情况。

解决方案

方案一:切换时强制同步密码值

修改密码可见性切换的逻辑,在切换showPassword的同时,手动触发一次密码状态的更新,确保原生输入框同步最新值:

<TextInput.Icon
  icon={showPassword ? 'eye-off' : 'eye'}
  color='white'
  forceTextInputFocus={false}
  onPress={() => {
    setShowPassword(prev => !prev);
    // 强制同步当前密码值,避免原生输入框清空
    setPassword(prev => prev);
  }}
/>

方案二:使用ref直接操作原生组件

通过useRef获取TextInput实例,切换可见性后手动设置原生输入框的文本内容:

import { useRef } from 'react';

// 组件内部定义ref
const passwordInputRef = useRef(null);

// 修改TextInput添加ref属性
<TextInput
  ref={passwordInputRef}
  // 其他原有属性保持不变
  right={
    showIcon && (
      <TextInput.Icon
        icon={showPassword ? 'eye-off' : 'eye'}
        color='white'
        forceTextInputFocus={false}
        onPress={() => {
          setShowPassword(!showPassword);
          // 切换后手动同步文本内容
          if (passwordInputRef.current) {
            passwordInputRef.current.setNativeProps({ text: password });
          }
        }}
      />
    )
  }
/>

方案三:移除textContentType='password'(可选)

如果不需要密码自动填充功能,尝试移除textContentType='password'属性,避免其与secureTextEntry的切换逻辑产生冲突:

// 移除该行代码
textContentType='password'

内容的提问来源于stack exchange,提问作者Camilo Parrado

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 15:07:05