简体   繁体   中英

javascript/react keydown vs onClick

I have a weird interaction happening on my javascript calculator. As far as I can tell, my keydown event and my onClick should be doing the same thing. However the outcome is different.

A live version of the calculator is here: https://aaronrbetts.github.io/Calculator/

if i click: '7+' the output shows 7+.

if i use the numPad and type '7+' i get '14+'.

  handleKeyPress(e) {
// Check if key pressed is in calc buttons array
var result = buttonObjects.find(obj => {
  return obj.keyCode === e.keyCode
});

if(result) {
  // handle input if key pressed is on calculator
  this.handleInput(result.value, result.type);
}

}

  render() {
document.addEventListener("keydown", this.handleKeyPress)

      {buttonObjects.map((key, idx) => (
        <button key={idx} id={key.id} onClick={() => this.handleInput(key.value, key.type)}>{key.value}</button>
      ))}

addEventListener is called in render , so every time your component rerenders, handleKeyPress will run an additional time when a key is held down. To solve this, move this call to componentDidMount .

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