[英]Eslint doesn't recognize a FunctionComponent defined inside a function and complains about using a hook inside it
I have a component-creating function:我有一个组件创建功能:
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
}
That I use to generate components for my app ( MobileOnly
, TabletOnly
, etc.).我用来为我的应用程序生成组件( MobileOnly
、 TabletOnly
等)。
However eslint complains about the use of the useViewportCategory
hook and pretents me from running the app:然而 eslint 抱怨useViewportCategory
钩子的使用,并假装我运行应用程序:
React Hook "useViewportCategory" is called in function "component: FunctionComponent" which is neither a React function component or a custom React Hook function react-hooks/rules-of-hooks React Hook "useViewportCategory" 在函数 "component: FunctionComponent" 中调用,它既不是 React 函数组件也不是自定义 React Hook 函数 react-hooks/rules-of-hooks
Interestingly, casting the component in TypeScript fixes the error:有趣的是,在 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
What is going on here?这里发生了什么?
Why does es lint recognize function components defined directly inside module scope but not here?为什么 es lint 识别直接在模块范围内定义的函数组件而不是在这里?
What can I do to fix this error without type casting / disabling eslint rule?我该怎么做才能在不进行类型转换/禁用 eslint 规则的情况下修复此错误?
Try writing your function in PascalCase:尝试在 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 rule expects function to be written in PascalCase. Lint 规则期望函数以 PascalCase 编写。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.