【发布时间】:2019-10-03 11:54:40
【问题描述】:
我是 React 的初学者,但遇到了一些问题。我想在componentDidMount() 方法中添加一些事件侦听器,另外我需要捕获事件以查找单击了哪个键。
我想在componentWillUnmount() 方法中删除它。我用额外的功能做到了。但是有一些问题。经过一段时间后(例如一秒钟后),我想更新父组件中的状态(触发组件卸载并且我做到了),但是有一个问题我无法删除componentWillUnmount() 中的事件侦听器,所以请帮助我。
这是我的代码
import React, { Component } from 'react';
class Element extends Component {
componentDidMount(){
const {attributes, startTime, timeOut, automaticAnswer} ={...this.props};
document.addEventListener('keypress', function func(e){
that.handleClick(e, startTime, attributes.keyBoardKey, false, timeOut, func)});
}
handleClick(event, startTime, realAnswer, automaticAnswer, timeOut, func){
this.props.fillAnswer(event.key ? event.key : '', startTime, realAnswer, automaticAnswer, timeOut);
document.removeEventListener('keypress', func);
}
render() {
const {attributes, startTime, timeOut, automaticAnswer} ={...this.props};
if(automaticAnswer ){
this.handleClick('', startTime, attributes.keyBoardKey, true, timeOut);
}
return (
<span className={attributes.className}>{attributes.value}</span>
);
}
}
export default Element;
【问题讨论】:
-
您好,您能描述一下您实际需要执行哪些功能吗?
-
这是一个测试。屏幕上出现了一些用不同颜色书写的单词。用户必须按下正确的键(它写在描述中)。用户有 1 秒时间回答问题。一秒钟后,必须出现另一个组件,它显示您的答案有多少是正确的。然后用户单击“下一步”按钮,出现另一个单词......一次又一次
-
您是否尝试过其他活动?
-
例如哪个事件?我需要按键事件
-
键盘的事件主要有3个:keydown、keypress、keyup。你可以使用其中的任何一个。
标签: javascript reactjs