keydown触发两次的eventListener回调函数

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

我的右侧有一个菜单,左侧有相关说明,我想在按向下箭头或向上箭头键时更改菜单中的选定项目。 但每次我按下按键时,回调函数都会触发两次,并两两滚动而不是一一滚动!我不知道我的代码有什么问题。

我在

componentDidMount
中定义了一个事件监听器,如下所示:

public componenDidMount () {
 global?.window && global?.document.addEventListener('keydown', e => this.handleKeyPress(e));
}

和回调:

private handleKeyPress = (event: KeyboardEvent) => {
    const {activeType} = this.state;
    const {allSolutions} = this.props;

    const index = allSolutions.findIndex(x => x === activeType);
    if (event.key === 'ArrowDown') {
      this.scrollToSolutions(allSolutions[index + 1]);
    } else if (event.key === 'ArrowUp') {
      this.scrollToSolutions(allSolutions[index - 1]);
    }
  }

滚动到解决方案:

private scrollToSolutions = (id?: number) => {
    const item = document.getElementById(id?.toString() ? id.toString() : '');
    this.setState({activeType: id});
    if (item) {
      item.scrollIntoView({block: 'center'});
    }
}

感谢您的任何建议。

reactjs next.js addeventlistener keydown js-scrollintoview
1个回答
0
投票

确保 componentDidMount 不会被多次调用,因为这会添加多个事件侦听器。 您的生命周期方法名称有一个拼写错误(componenDidMount应该是componentDidMount)。如果名称不正确,该方法将不会作为生命周期方法被调用,如果在代码中的其他位置手动调用它,则可能会导致多个事件侦听器。

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