我有一个组件创建函数:
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
钩子并假装我停止运行该应用程序:
useViewportCategory" 在函数 "component: FunctionComponent" 中调用,它既不是 React 函数组件也不是自定义 React Hook 函数 react-hooks/rules-of-hook
有趣的是,在 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 中编写。