我有一个菜单在右侧和相关的说明在左侧,我想改变所选的项目在菜单中,当我按下箭头向下或箭头向上键.但每次我按下键的回调函数触发两次,滚动两个两个不是一个接一个!!我不知道我的代码有什么问题.
我在componentDidMount
中定义了一个事件侦听器,如下所示:
public componentDidMount () {
global?.window && global?.document.addEventListener('keydown', e => this.handleKeyPress(e));
}
字符串
和callBack:
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]);
}
}
型
scrollToSolution:
private scrollToSolutions = (id?: number) => {
const item = document.getElementById(id?.toString() ? id.toString() : '');
this.setState({activeType: id});
if (item) {
item.scrollIntoView({block: 'center'});
}
}
型
谢谢你的任何建议。
1条答案
按热度按时间czq61nw11#
请确保componentDidMount未被多次调用,因为这将添加多个事件侦听器。您在生命周期方法名称中存在拼写错误(* componentDidMount * 应为 componentDidMount)。如果名称不正确,则该方法不会作为生命周期方法调用,并且如果在代码中的其他位置手动调用该方法,则可能导致多个事件侦听器。