首页 > 解决方案 > 有没有办法改变 React 中输入的类型?

问题描述

所以我尝试了以下方法,我似乎无法更改输入的类型。因此,相同的输入可以是文本或密码类型,但我无法在两者之间切换。这是一个语义 UI 输入。(来自语义-ui-react)

   const [inputType, setInputType] = useState('password'||'text')

在我的 JSX 中:

   <Input type={inputType} value={inputValue} onChange={handleInput} className="landingInput" placeholder={inputPlaceholder} />

初始化时:

  setInputType('text'); 

事件发生后:

  setInputType('password'); // should update html template with type="password" but it doesn't

useEffect 用于确保状态已更新,其他所有钩子都按预期工作。这可能是一种安全预防措施吗?你能想出一种避免创建新输入的方法吗?

谢谢

标签: javascripthtmlreactjssemantic-ui-reactuse-state

解决方案


切换输入类型很简单,这里我使用一个按钮将输入类型切换为textpassword在此处查看工作演示。

检查更新的代码块

const App=()=>{
  const [inputType, setInputType] = useState('text');
  const inputPlaceholder = 'Add Here';
  const handleInput =()=>{}

  const toggleInput = ()=>{
setInputType(inputType === 'password' ? 'text': 'password')
  }
    return (
      <div>
        <input type={inputType} value="password" onChange={handleInput} className="landingInput" placeholder={inputPlaceholder} />
        <button onClick={toggleInput} >Toggle type</button>
      </div>
    );
}

推荐阅读