是否可以在React中更改输入的类型?

问题描述 投票:0回答:2

所以我尝试了以下操作,但似乎无法更改输入的类型。因此,相同的输入可以是文本类型或密码类型,但是我不能在两者之间切换。这是一个语义UI输入。 (来自semantic-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用于确保状态已更新,其他所有钩子均按预期工作。这可以作为安全预防措施吗?您能想到一种避免创建新输入的方法吗?

谢谢

javascript html reactjs semantic-ui-react use-state
2个回答
0
投票

您必须卸载组件以使其工作,因为组件类型的工作方式与defaultValue相同,并在安装时初始化。

inputType === `password` && <Input type="password" value={inputValue}/>
inputType === `text` && <Input type="text" value={inputValue}/>

0
投票

切换输入类型很容易,请检查工作演示Here

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>
    );
}
© www.soinside.com 2019 - 2024. All rights reserved.