reactjs - Eslint 无法识别函数内部定义的 FunctionComponent 并抱怨在其中使用钩子
问题描述
我有一个组件创建功能:
import useViewportCategory from '../../../hooks/viewport/useViewportCategory'
type CreateViewportRestrictor = (
displayName: string,
settings: { showOnDesktop?: boolean, showOnTablet?: boolean, showOnMobile?: boolean },
) => FunctionComponent
const createViewportRestrictor: CreateViewportRestrictor = (
displayName,
{ showOnDesktop = false, showOnTablet = false, showOnMobile = false },
) => {
const component: FunctionComponent = ({ children }) => {
const viewportCategory = useViewportCategory()
if (viewportCategory === 'DESKTOP' && !showOnDesktop) return null
if (viewportCategory === 'MOBILE' && !showOnMobile ) return null
if (viewportCategory === 'TABLET' && !showOnTablet ) return null
return <>{children}</>
}
component.displayName = displayName
return component
}
我用来为我的应用程序生成组件(MobileOnly
,TabletOnly
等)。
然而 eslint 抱怨使用useViewportCategory
钩子并假装我无法运行应用程序:
React Hook "useViewportCategory" 在函数 "component: FunctionComponent" 中被调用,它既不是 React 函数组件也不是自定义 React Hook 函数 react-hooks/rules-of-hooks
有趣的是,在 TypeScript 中强制转换组件可以修复错误:
const component: FunctionComponent = (({ children }) => {
const viewportCategory = useViewportCategory()
if (viewportCategory === DESKTOP && !showOnDesktop) return null
if (viewportCategory === MOBILE && !showOnMobile ) return null
if (viewportCategory === TABLET && !showOnTablet ) return null
return <>{children}</>
}) as FunctionComponent
这里发生了什么?
为什么 es lint 可以识别直接在模块范围内定义的功能组件,而不是在这里?
如果不进行类型转换/禁用 eslint 规则,我该怎么做才能修复此错误?
解决方案
尝试用 PascalCase 编写函数:
const Component: FunctionComponent = (({ children }) => {
const viewportCategory = useViewportCategory()
if (viewportCategory === DESKTOP && !showOnDesktop) return null
if (viewportCategory === MOBILE && !showOnMobile ) return null
if (viewportCategory === TABLET && !showOnTablet ) return null
return <>{children}</>
})
Lint 规则要求函数用 PascalCase 编写。
推荐阅读
- laravel - Laravel 雄辩与条件
- html - 需要使用 CSS 在 HTML 中创建交错堆叠的网格
- transloco - Transloco 配置 missingHandler.logMissingKey
- java - 连接对方的Kafka需要配置什么信息
- c - 结构不显示 C 中输入的值
- sql - 如何根据另一列隔离一列?
- consul - 通过 CLI 使用 HTTP Endpoint Handler 配置 Consul Watches
- python - 如何更新通过 tf.get_variable 生成的内核值
- javascript - 如何让实体触发不同的实体鼠标悬停事件(D3)
- c++ - C++:为什么这不会导致悬空指针?