所以我尝试了以下操作,但似乎无法更改输入的类型。因此,相同的输入可以是文本类型或密码类型,但是我不能在两者之间切换。这是一个语义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用于确保状态已更新,其他所有钩子均按预期工作。这可以作为安全预防措施吗?您能想到一种避免创建新输入的方法吗?
谢谢
您必须卸载组件以使其工作,因为组件类型的工作方式与defaultValue
相同,并在安装时初始化。
inputType === `password` && <Input type="password" value={inputValue}/>
inputType === `text` && <Input type="text" value={inputValue}/>
切换输入类型很容易,请检查工作演示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>
);
}