首页 > 解决方案 > TypeScript:在定义 @typescript-eslint/no-use-before-define 之前使用了“handleFirstTab”

问题描述

我在 React 组件中有以下代码,TypeScript 给出以下错误:

'handleFirstTab' was used before it was defined @typescript-eslint/no-use-before-define

如果我将两个函数拆分为单独的文件并将它们相互导入,那么错误就会消失。有没有一种方法可以让我在同一个文件中同时拥有这两个功能而不禁用@typescript-eslint/no-use-before-define并且错误会消失。谢谢。

  const handleMouseDownOnce = (): void => {
    document.body.classList.remove('user-is-tabbing')
    window.removeEventListener('mousedown', handleMouseDownOnce)
    window.addEventListener('keydown', handleFirstTab)
  }

  const handleFirstTab = (e: KeyboardEvent): void => {
    if (e.code === 'Tab') {
      document.body.classList.add('user-is-tabbing')
      window.removeEventListener('keydown', handleFirstTab)
      window.addEventListener('mousedown', handleMouseDownOnce)
    }
  }

标签: typescripttypestype-conversion

解决方案


当您使用关键字或使用定义变量(或函数)时constlet它不会Hoist作为函数声明functionvar

如果您想将它们都放在同一个文件中,则需要更改代码,如下所示:

  function handleMouseDownOnce(): void {
    document.body.classList.remove('user-is-tabbing')
    window.removeEventListener('mousedown', handleMouseDownOnce)
    window.addEventListener('keydown', handleFirstTab)
  }

  function handleFirstTab(e: KeyboardEvent): void{
    if (e.code === 'Tab') {
      document.body.classList.add('user-is-tabbing')
      window.removeEventListener('keydown', handleFirstTab)
      window.addEventListener('mousedown', handleMouseDownOnce)
    }
  }

推荐阅读