简体   繁体   中英

React document.addEventListener is detecting multiple keypresses

I am trying to create a keypress listener for my React Js calculator app and when I add the event listener in, it detects additional key presses the more I press. Is there a better place to put the event listener? When I press 1234, I get

122333344444444

 /****************Button Component*************/
class CalcApp extends React.Component {

state = {
  value: null,
  displayNumbers: '0',
  selectedNumbers: [],
  calculating: false,
  operator:null
 };



selectMath = (selectedMath) =>{
const {displayNumbers, operator,value} = this.state;
const nextValue = parseFloat(displayNumbers)
console.log(selectedMath);

 /**do math and other methods*/

render() {
document.addEventListener('keydown', (event) => {
    const keyName = event.key;
  if(/^\d+$/.test(keyName)){
    this.selectButton(keyName)
    console.log(keyName);
    }
  });
return (
    <div>
        <Display displayNumbers={this.state.displayNumbers}
        selectedNumbers={this.state.selectedNumbers}/>
        <Button selectedNumbers={this.state.selectedNumbers}
                selectButton ={this.selectButton}
                selectC = {this.selectC}
                displayNumbers={this.state.displayNumbers}
                selectDot = {this.selectDot}
                selectMath = {this.selectMath}/>
    </div>
);
}
}

let domContainer = document.querySelector('#app');
ReactDOM.render(<CalcApp />, domContainer);

Remove document.addEventListener listener from render() .

The method is being called whenever the components needs to re-render (changes of state / props ) which attaches yet another event listener.

Suggestion: Move document.addEventListener to componentDidMount() - executed only once, and remove it via document.removeEventListener on componentWillUnmount to prevent memory leaks.

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