javascript - 有没有办法改变 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 用于确保状态已更新,其他所有钩子都按预期工作。这可能是一种安全预防措施吗?你能想出一种避免创建新输入的方法吗?
谢谢
解决方案
切换输入类型很简单,这里我使用一个按钮将输入类型切换为text
和password
。在此处查看工作演示。
检查更新的代码块
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>
);
}
推荐阅读
- python - 什么代码不允许我将项目添加到库存?
- sql - BiqQuery 查找字符串中的小数点并删除所有小数点(包括小数点)
- python - 无法安装 tesseract-ocr
- php - Laravel Backpack 过滤器范围量输入宽度太小
- shell - 如何删除从我想要的单词开始的单词,直到找到模式(即使它在接下来的几行中)?
- draftjs - 如何在 Draft.js 编辑器中将嵌入链接与来自 html 的图像转换?
- javascript - 将 midiFiles 解析为二进制文件,然后使用 JS 客户端保存
- xml - XSLT - 将 XML 文档转换为按字母顺序排列的元素
- reactjs - 使用 axios 进行异步 API 调用后出现 TypeError
- javascript - Svelte on:改变来得太晚