NextJS动态导入问题

时间:2021-07-07 16:09:37

标签: reactjs typescript next.js

我在使用 dynamicNextJS 导入时遇到了一个非常奇怪的问题。

我正在像这样导入一个组件:

const Spinner = dynamic(() => import('components/ui/Spinner').then(mod => mod.Spinner))

Spinner.tsx

import {useEffect, useState} from 'react'
import PulseLoader from 'react-spinners/PulseLoader'

import {FadeHOC} from '.'
import theme from 'utils/theme'


interface Props {
  inline?: boolean
}

const TIMEOUT = 1000

export const Spinner = ({inline}: Props) => {

  const [show, setShow] = useState(false)

  useEffect(() => {
    
    const timeout = setTimeout(
      () => setShow(true),
      TIMEOUT
    )
    
    return () => clearTimeout(timeout)
  }, [])

  return (
    show
      ? <FadeHOC>
          <PulseLoader size={10} margin={3} color={theme.color} css={inline ? 'margin-left: 14px;' : 'display: block; text-align: center; margin: 100px auto;'} />
        </FadeHOC>
      : null
  )
}

dynamic 导入语句中,我收到了 TypeScript 投诉:

Argument of type '() => Promise<(({ inline }: Props) => JSX.Element) | ComponentClass<never, any> | FunctionComponent<never> | { default: ComponentType<never>; }>' is not assignable to parameter of type 'DynamicOptions<{}> | Loader<{}>'.
  Type '() => Promise<(({ inline }: Props) => JSX.Element) | ComponentClass<never, any> | FunctionComponent<never> | { default: ComponentType<never>; }>' is not assignable to type '() => LoaderComponent<{}>'.
    Type 'Promise<(({ inline }: Props) => Element) | ComponentClass<never, any> | FunctionComponent<never> | { default: ComponentType<never>; }>' is not assignable to type 'LoaderComponent<{}>'.
      Type '(({ inline }: Props) => Element) | ComponentClass<never, any> | FunctionComponent<never> | { default: ComponentType<never>; }' is not assignable to type 'ComponentType<{}> | { default: ComponentType<{}>; }'.
        Type '({ inline }: Props) => JSX.Element' is not assignable to type 'ComponentType<{}> | { default: ComponentType<{}>; }'.
          Type '({ inline }: Props) => JSX.Element' is not assignable to type 'FunctionComponent<{}>'.
            Types of parameters '__0' and 'props' are incompatible.
              Type '{ children?: ReactNode; }' has no properties in common with type 'Props'.ts(2345)

我不知道投诉的内容,非常感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

@brc-dd 是对的,尽管解释为什么会这样:

dynamic 是这样输入的:

export default function dynamic<P = {}>(dynamicOptions: DynamicOptions<P> | Loader<P>, options?: DynamicOptions<P>): React.ComponentType<P>;

所以它希望你返回 React.ComponentType<P>,这意味着:

type ComponentType<P = {}> = ComponentClass<P> | FunctionComponent<P>;

FunctionComponent 是:

interface FunctionComponent<P = {}> {
        (props: PropsWithChildren<P>, context?: any): ReactElement<any, any> | null;
        propTypes?: WeakValidationMap<P>;
        contextTypes?: ValidationMap<any>;
        defaultProps?: Partial<P>;
        displayName?: string;
    }

所以你必须有带有 children 键的道具。如果您不想弄乱您的组件界面并且它实际上不接受子组件,那么您可以在组件 Props 界面中输入 children?: never;