如何使用React钩子阻止输入元素从不受控制的切换到受控的控制,反之亦然?

时间:2020-04-14 14:39:31

标签: javascript reactjs react-hooks react-hook-form

大家好,我在使用React钩子验证表单时遇到了一些问题。单击提交

的提交按钮时,我总是收到错误消息

index.js:1警告:组件将电子邮件类型的受控输入更改为不受控制。输入元素不应从受控状态切换到非受控状态(反之亦然)。在组件的生命周期中决定使用受控还是不受控制的输入元素。

这是我的代码。

    const [formData, setFormData] = useState({
  email:'',
  password:'',
  emailError:'',
  passwordError:''
 }) 



 const handleEmailChange = e => setFormData({email: e.target.value})

 const handlePasswordChange = e => setFormData({password: e.target.value})

 //validate
 const validate = () => {
  let inputError = false
  const errors = {
   emailError:'',
   passwordError:''
  }
  if(!formData.email) {
   inputError = true
   errors.emailError = 'Please enter a valid email'
  } 
  else if(!formData.email.match(emailRegex)) 
  {
   inputError = true
   errors.emailError = (
    <span style={{color:'red'}}>Your email address must be valid</span>
   )
  }

  if(formData.password.length < 4){ 
   inputError = true
   errors.passwordError = 'Your password must contain more than 4 characters'
  }

  setFormData({
   ...errors
  })

  return inputError
 }

 const onSubmit = e => {
  e.preventDefault();

  const err = validate();

  if(!err){`
   setFormData(formData)
  }
 }

我的JSX

   <FormContainer>
   <div className="form-container">
    <form >
     <h1>Sign in</h1>
     <div className="input-container">
      <input className={formData.emailError ? 'input-error input-empty' : 'input-empty'}
       value={formData.email} 
       type="email"
        required
        onChange={e => handleEmailChange(e)}
        />
      <label>Email or Phone Number</label>
      <span style={{color: '#db7302'}}>{formData.emailError}</span>
     </div>
     <div className="input-container">
      <input 
      className={formData.passwordError ? 'input-error input-empty' : 'input-empty'}
       type="password" 
       value={formData.password} 
       required
       onChange={e => handlePasswordChange(e)}
       />
      <label>Password</label>
      <span style={{color: '#db7302'}}>{formData.passwordError}</span>
     </div>
     <div className="input-container">
      <Button href="/" onClick={e => onSubmit(e)} type="submit">Sign in</Button>
     </div>
     <label className="checkbox-container">
      Remember me
     <input type="checkbox" checked />
      <span className="checkmark"></span>
     </label>
     <Link to="/" className="need-help">Need Help?</Link>
     <div className="bottom-form">
      <img src={fbLogo} alt="" />
      <Link to="/" className="login-fb">
       Login with facebook
     </Link>
     <br/>
     <br/>
     <span style={{color:'#999'}}>New to netflix?</span>&nbsp;
     <Link to="/" className="signup-txt">Sign up now</Link>
     </div>
    </form>
   </div>
  </FormContainer>

1 个答案:

答案 0 :(得分:1)

设置formData时,不会包含所有值,因此与其将email作为空字符串,它变成了undefined,React决定了{{ 1}}不受控制,如果其值为input

为防止这种情况,请在设置undefined时包括表格的先前值:

formData