繁体   English   中英

根据 boolean state Reactjs 动态更改输入类型

[英]dynamically change input type based on boolean state Reactjs

我正在创建一个允许用户查看密码的复选框。 我正在为 UI 组件使用 Material UI React。 我有复选框设置和工作。 输入类型的初始 state 是密码,当单击复选框时,它会更改为文本,但是一旦再次单击,它不会恢复为密码,无论checkState的 state 都保持在“文本”类型

 // state const [checkState, setCheckState] = useState({ checkedA: false, type: 'password', }); // checkbox handle change function const handleChange = (event) => { console.log(checkState); setCheckState({...checkState, checkedA: event.target.checked, type: checkState? 'text': 'password' }); } // textField Comp <TextField id="standard-basic" label="Password" type={checkState.type} onChange={e => setData({...data, password: e.target.value})} onKeyDown={(e)=> {keyDown(e)}} />

checkState似乎总是一个真实的值(它是一个对象)。 您想根据checkState.type的当前值而不是checkState对象的真实性来更改它。

setCheckState({
  checkedA: event.target.checked,
  type: checkState.type === 'password' ? 'text' : 'password'
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM