React document.addEventListener正在检测多个按键

问题描述 投票:1回答:1

我正在尝试为我的React Js计算器应用程序创建一个按键监听器,当我添加事件监听器时,它会检测到我按下的更多按键。是否有更好的地方放置事件监听器?当我按1234时,我明白了

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);
javascript reactjs
1个回答
1
投票

Remove document.addEventListener listener from render().

只要组件需要重新渲染(state / props的更改)附加另一个事件监听器,就会调用该方法。

建议:将document.addEventListener移至componentDidMount() - 仅执行一次,并通过document.removeEventListener上的componentWillUnmount将其删除以防止内存泄漏。

© www.soinside.com 2019 - 2024. All rights reserved.