Eslint无法识别在函数内部定义的FunctionComponent,并且抱怨在函数内部使用钩子

时间:2020-01-31 18:30:45

标签: reactjs typescript react-hooks eslint typescript-eslint

我具有创建组件的功能:

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
}

我用来为我的应用生成组件(MobileOnlyTabletOnly等)。

但是eslint抱怨使用useViewportCategory钩子,并假装我无法运行该应用程序:

在函数“ component:FunctionComponent”中调用“ React Hook”“ useViewportCategory”,它既不是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规则的情况下该如何解决此错误?

1 个答案:

答案 0 :(得分:1)

尝试在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编写。