简体   繁体   中英

Conflicting events: onKeyPress & onClick

I have a from like this:

在此处输入图片说明

With the following code:

<form onKeyPress={this.login.bind(this)}>
    <input type="text" placeholder="username"/>
    <input type="password" placeholder="password"/>
    <button type="button" onClick={this.login.bind(this)}>Log In</button>
</form>

While I have the login() method like below:

login(e){
    if((e.type==='keypress' && e.which===13) || e.type==='click'){        
            //Do login operations:
            this.props.store.login()//the method inside MobX store
    }
}

On following scenarios, there is no errors and I can login:

  1. I click on the login button with mouse
  2. I press Enter while the login button is NOT focused

But the following 3rd scenario, gives me errors due to the login operations being called twice:

  1. When I press Enter while login button IS focused (for example login button is focused by pressing tab key)

I wonder what is the best practice by which I can avoid the errors of 3rd scenario. I looked through other related SO questions but I couldn't figure out the best practice.


I forgot to mention I'm using ReactJS with MobX.

Solved the problem by moving onKeyPress attribute from <form> tag to text-type <input> tags:

<form>
    <input type="text" placeholder="username" onKeyPress={this.login.bind(this)}/>
    <input type="password" placeholder="password" onKeyPress={this.login.bind(this)}/>
    <button type="button" onClick={this.login.bind(this)}>Log In</button>
</form>

You could also use the onSubmit event if it suits your use case better:

Example ( JS Bin )

class App extends Component {
  login = (e) => {
    e.preventDefault();
    console.log('login');
  }
  render() {
    return (
      <form onSubmit={this.login}>
        <input type="text" placeholder="username" />
        <input type="password" placeholder="password" />
        <button type="submit">Log In</button>
      </form>
    );
  }
}

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