簡體   English   中英

使用 componentDidMount 和 componentWillUnmount 在 React 中添加和刪除事件監聽器

[英]Add and Remove event listeners in React with componentDidMount and componentWillUnmount

componentDidMount() {
      document.addEventListener('mousemove', (e) => this.customCursorFollow(e));
      document.addEventListener('click', this.customCursorClick);
  }

  componentWillUnmount() {
      document.removeEventListener('mousemove', (e) =>
        this.customCursorFollow(e)
      );
      document.removeEventListener('click', this.customCursorClick);
  }

  customCursorFollow(e) {
    const cursor = document.querySelector('.cursor');
    cursor.setAttribute(
      'style',
      'top: ' + (e.pageY - 20) + 'px; left: ' + (e.pageX - 20) + 'px;'
    );
  }

  customCursorClick() {
    const cursor = document.querySelector('.cursor');
    cursor.classList.add('expand');

    setTimeout(() => {
      cursor.classList.remove('expand');
    }, 500);
  }

在 React 中,我的 addEvent 偵聽器和刪除事件偵聽器無法正常工作。 具體來說,removeEventListener 不適用於 customCursorFollow。

還:這是在 React 中添加事件和刪除事件偵聽器的最佳方式嗎? 使用 componentDidMount 和 componentWillUnmount?

對於addEventListenerremoveEventListener ,一個主要要求是傳遞給addEventListener的 function 引用應該與傳遞給removeEventListener的引用相同。

現在,當您使用箭頭函數時,引用會有所不同,因此無法正確刪除偵聽器。

由於您只需要傳遞事件,因此您不需要將偵聽器作為箭頭 function。

componentDidMount() {
      document.addEventListener('mousemove', this.customCursorFollow);
      document.addEventListener('click', this.customCursorClick);
  }

  componentWillUnmount() {
      document.removeEventListener('mousemove', this.customCursorFollow);
      document.removeEventListener('click', this.customCursorClick);
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM