You need to enable JavaScript to run this app. 如何为多个输入字段添加带眼睛按钮的相同密码显隐切换效果?
优惠活动
大模型
产品
解决方案
定价
更多

如何为多个输入字段添加带眼睛按钮的相同密码显隐切换效果?

问题原因

你写的第二个密码字段代码存在两处错误:

  • RecoveryInput组件的type属性判断条件错误:你用了密码内容状态password2作为判断依据,而不是专门控制显隐的show2状态
  • type属性的密码值无效:HTML原生输入框仅识别password作为密码类型,你写的senha是葡萄牙语的密码表述,不属于合法的input type值,浏览器无法按密码逻辑处理输入内容

修复后的代码

const [show2, setShow2] = useState(false)
const [password2, setPassword2] = useState('')

<RecoveryGroup>
  <ButtonRecovery>
    <RiLockPasswordLine size={22} />
  </ButtonRecovery>
  <RecoveryInput 
    value={password2} 
    type={show2 ? 'text' : 'password'} 
    placeholder='Digite sua senha aqui' 
    onChange={({ target }) => setPassword2(target.value)} 
  />
  <ButtonEye onClick={() => setShow2(!show2)} type='button'>
    {show2 ? <FaEye size={18} /> : <FaEyeSlash size={18} />}
  </ButtonEye>
</RecoveryGroup>

优化建议

如果后续还有更多密码字段需要实现同样效果,可以把这部分逻辑封装为可复用的PasswordInput组件,避免重复编写状态控制和UI代码,示例如下:

const PasswordInput = ({ placeholder, value, onChange }) => {
  const [show, setShow] = useState(false)
  return (
    <RecoveryGroup>
      <ButtonRecovery>
        <RiLockPasswordLine size={22} />
      </ButtonRecovery>
      <RecoveryInput 
        value={value} 
        type={show ? 'text' : 'password'} 
        placeholder={placeholder} 
        onChange={onChange} 
      />
      <ButtonEye onClick={() => setShow(!show)} type='button'>
        {show ? <FaEye size={18} /> : <FaEyeSlash size={18} />}
      </ButtonEye>
    </RecoveryGroup>
  )
}

使用时直接调用组件即可:

// 第一个密码框
<PasswordInput 
  placeholder="Digite sua senha aqui"
  value={password}
  onChange={({ target }) => setPassword(target.value)}
/>
// 第二个密码框
<PasswordInput 
  placeholder="Digite sua senha novamente"
  value={password2}
  onChange={({ target }) => setPassword2(target.value)}
/>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 17:45:03