Next.js:“组件”不能用作 JSX 组件

Ján*_*nos 27 reactjs next.js

为什么我在这一行中遇到错误?

<Provider store={store}>{getLayout?(<Component {...pageProps} />)}</Provider>
Run Code Online (Sandbox Code Playgroud)
(parameter) Component: NextComponentType<NextPageContext, any, {}> & NextPageWithLayout
'Component' cannot be used as a JSX component.
  Its element type 'ReactElement<any, any> | Component<{}, any, any>' is not a valid JSX element.
    Type 'Component<{}, any, any>' is not assignable to type 'Element | ElementClass'.
      Type 'Component<{}, any, any>' is not assignable to type 'ElementClass'.
        The types returned by 'render()' are incompatible between these types.
          Type 'React.ReactNode' is not assignable to type 'import("/Users/kukodajanos/Workspace/Tikex/Portal/Team/node_modules/@types/styled-jsx/node_modules/@types/react/index").ReactNode'.
            Type '{}' is not assignable to type 'ReactNode'.
Run Code Online (Sandbox Code Playgroud)

完整组件:

<Provider store={store}>{getLayout?(<Component {...pageProps} />)}</Provider>
Run Code Online (Sandbox Code Playgroud)

我将 Next.js 升级到最新版本,也许这会导致一些问题?

"next": "12.1.0",
Run Code Online (Sandbox Code Playgroud)

我需要在 中同时使用普通参考和 TypeScript 参考吗package.json,你知道吗?

(parameter) Component: NextComponentType<NextPageContext, any, {}> & NextPageWithLayout
'Component' cannot be used as a JSX component.
  Its element type 'ReactElement<any, any> | Component<{}, any, any>' is not a valid JSX element.
    Type 'Component<{}, any, any>' is not assignable to type 'Element | ElementClass'.
      Type 'Component<{}, any, any>' is not assignable to type 'ElementClass'.
        The types returned by 'render()' are incompatible between these types.
          Type 'React.ReactNode' is not assignable to type 'import("/Users/kukodajanos/Workspace/Tikex/Portal/Team/node_modules/@types/styled-jsx/node_modules/@types/react/index").ReactNode'.
            Type '{}' is not assignable to type 'ReactNode'.
Run Code Online (Sandbox Code Playgroud)

Jak*_*tra 23

我通过删除yarn.lock 文件修复了这个问题。跨软件包版本的类型存在问题。

“预安装”:“npx npm-force-分辨率”“@types/react”:“17.0.30”

  • 必须删除“node_modules”和“yarn.lock”,然后运行“yarn”,它适用于 NextJS 12 =&gt; 13 升级 (3认同)
  • 对于那些使用 `yarn` 的用户,只需将“resolutions”: {} 添加到 package.json 中,这样就不需要 `npm-force-resolutions` 了。 (2认同)

cam*_*ser 16

没有什么可以“认真”推荐的,但我能够通过省略类型来解决该错误:

function MyApp({ Component, pageProps }: AppProps) {
  const AnyComponent = Component as any;
  return <AnyComponent {...pageProps} />;
}
Run Code Online (Sandbox Code Playgroud)

  • 我知道 Typescript 的人不喜欢“any”,但是说真的,这个错误让我非常困惑,我完全陷入困境,搜索了几个小时,尝试了相同类型的解决方案,但使用“as JSX.Element”,但没有。不工作。这是唯一对我有用的东西所以谢谢@camposer (8认同)