简体   繁体   中英

Why does react form's onSubmit fire after every keystroke, how to use enter button to submit form?

The goal is to submit a form by pressing enter button. so i added the onSubmit attribute to my react form. the form submits after every single key press. no problem, i probably just forgot to bind the submit method right? wrong, its a stateless functional component.

submit function:

const postLogin = (e) => {
    e.preventDefault()
    
    axios.post("http://<...>/users/login", {
      username,
      password
    }).then(result => {
      if (result.status === 200) {
        console.log(result.data)
        
        setAuthTokens(result.data.token);
        setRole(result.data.role);
      } else {
        setIsError(true);
      }
    }).catch(e => {
      setIsError(true);
    });
  }

form:

<Form onSubmit={postLogin}>
  <Input 
    type="username" 
    value={username}
    placeholder="username"
    onChange={e => setUserName(e.target.value)}
  />
  <Input 
    type="password" 
    value={password}
    placeholder="password"
    onChange={e => setPassword(e.target.value)}
  />
  <Button onClick={() => postLogin}>Sign In</Button>
  <Button onClick={postRegister({username, password})}>Register</Button>
</Form>

All components are styled components and match their element (form, button, input) i've also tried setting the onKeyPress listener on the password input and gave a condition like e => e.keyCode === 13 ? postLogin() : null e => e.keyCode === 13 ? postLogin() : null , which didnt work either.

How do i prevent this submit function from firing every keystroke, and use the enter button to submit form?

when calling setPassword or setUserName then your component rerenders, this causes the 2nd button to cause the register issue

remove the onClick handler in the second Button "register" because you are calling it every time you render the component.

so

  1. remove the onSubmit in Form
  2. fix the postLogin (adding () )
  3. fix postRegister (don't call it directly, but add it as callback)
<Form>
  <Input 
    type="username" 
    value={username}
    placeholder="username"
    onChange={e => setUserName(e.target.value)}
  />
  <Input 
    type="password" 
    value={password}
    placeholder="password"
    onChange={e => setPassword(e.target.value)}
  />
  <Button onClick={() => postLogin()}>Sign In</Button>
  <Button onClick={() => postRegister({username, password})}>Register</Button>
</Form>

Just add the button type

<Button type="submit">Sign In</Button>

Or remove the onSubmit from form tag and change

<Button onClick={() => postLogin()}>Sign In</Button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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