使用 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 侦听器和 remove 事件侦听器无法正常工作。具体来说,removeEventListener 不适用于 customCursorFollow。

另外:这是在 React 中添加事件和删除事件侦听器的最佳方式吗?使用 componentDidMount 和 componentWillUnmount?

对于 addEventListenerremoveEventListener,一个主要要求是传递给 addEventListener 的函数引用应该与传递给 removeEventListener.[=15 的函数引用相同=]

现在,当您使用箭头函数时,引用不同,因此无法正确删除侦听器。

因为你只需要传递事件,所以不需要监听器来作为箭头函数。

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

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