【问题标题】:Is there a way to change the type of an input in React?有没有办法改变 React 中输入的类型?
【发布时间】:2020-02-25 11:10:46
【问题描述】:

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

谢谢

【问题讨论】:

  • should update html template with type="password" ... 哪个模板?这个问题似乎缺少很多相关代码。
  • 我的意思是生成的html模板,我已经用相关的JSX更新了问题

标签: javascript html reactjs semantic-ui-react use-state


【解决方案1】:

切换输入类型很容易, 这里我使用一个按钮将输入类型切换为textpassword。 检查工作演示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>
    );
}

【讨论】:

  • setInputType(inputType === 'password' ? 'text': 'password') 成功了。非常感谢
  • @van 你需要语义 UI 小提琴吗??我也可以这样做
猜你喜欢
  • 2011-10-29
  • 1970-01-01
  • 2022-01-06
  • 1970-01-01
  • 1970-01-01
  • 2020-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多