typescript - 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)
}
}
解决方案
当您使用关键字或使用定义变量(或函数)时const
,let
它不会Hoist
作为函数声明function
var
如果您想将它们都放在同一个文件中,则需要更改代码,如下所示:
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)
}
}
推荐阅读
- java - 清单合并失败:uses-sdk:minSdkVersion
- matplotlib - matplotlib deprecated() 缺少 1 个必需的仅关键字参数:'removal'
- azure - Azure WebJob 在处理时突然关闭
- firebase - 在 react native 项目中安装 fire base 后,显示错误状态代码 1
- multithreading - Rust 中的多线程分支定界搜索
- c - 简单的计算器不适用于 C 中的大数字
- c# - C# ASP.NET 向单个用户添加属性列表
- graphviz - 如何通过消除蛇行和更好的边缘交叉来影响 Graphviz/dot 以制作更好的控制流图?
- javascript - Angular cdkDropList 拖动元素限制
- android - Motion UI ListView 安卓示例