【问题标题】:how to remove event listener from document in reactjs [duplicate]如何从reactjs中的文档中删除事件侦听器[重复]
【发布时间】: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


【解决方案1】:

下面的链接将有望匹配你的用例,我猜你的问题重复问题 This how you do it

constructor(props){
super(props);
this.onScroll = this.onScroll.bind(this);
}

componentDidMount() {
window.addEventListener('scroll', this.onScroll, false);
}

componentWillUnmount() {
window.removeEventListener('scroll', this.onScroll, false);
}

【讨论】:

  • 我看到了。但我的问题是我无法在我的函数中获得这样的事件
  • 任何具体的错误,比如你的“this”关键字有问题
  • 我犯了一个非常愚蠢的错误。谢谢大佬!!!
  • 你的回复对我帮助很大
猜你喜欢
  • 2020-11-13
  • 1970-01-01
  • 2018-01-25
  • 1970-01-01
  • 2012-09-10
  • 2012-07-18
  • 2010-10-10
  • 1970-01-01
相关资源
最近更新 更多