【问题标题】:'Component' cannot be used as a JSX component. Nextjs\'Component\' 不能用作 JSX 组件。下一步
【发布时间】:2022-12-20 00:12:58
【问题描述】:

这是 _app.tsx 的样子:

function MyApp({ Component, pageProps }: AppProps) {
  return <Component {...pageProps} />
}

我在构建项目时遇到此错误:

Type error: 'Component' cannot be used as a JSX component.
  Its element type 'ReactElement<any, any> | Component<{}, any, any> | null' is not a valid JSX element.
    Type 'Component<{}, any, any>' is not assignable to type 'Element | ElementClass | null'.
      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/user/node_modules/@types/react/index").ReactNode'.
            Type '{}' is not assignable to type 'ReactNode'.

这些是反应版本:

"react": "17.0.2",
"react-dom": "17.0.2",
"@types/react": "17.0.26",

我尝试切换到 18 版本,它起作用了,但是我收到了这个错误:Hydration failed because the initial UI does not match what was rendered on the server

【问题讨论】:

  • 你传递给 Component 道具的是什么?
  • @DaveNewton 你是说这个:{...pageProps}
  • 确保您尝试呈现的页面是有效的 React 组件。请记住 Component 在此上下文中是您的页面组件,因此它表示您的页面组件不是有效的 React 组件。
  • 不,我的意思是你将什么作为 Component 道具传递给 MyApp
  • @DaveNewton 如果我理解正确,那么我不会将任何道具传递给MyApp,因为 nextjs 确实传递了一些东西,我不知道是什么。这是 _app.tsx 文件

标签: javascript reactjs typescript next.js


【解决方案1】:

将以下代码添加到package.json 文件中

"resolutions": {
  "@types/react": "17.0.2",
  "@types/react-dom": "17.0.2"
}

然后重新安装软件包

yarn
  • 如果使用 npm
npm i

【讨论】:

    【解决方案2】:

    我认为那是因为你没有在你的项目中正确设置打字稿。我认为,目前,当你安装 next.js 时,你应该可以选择 typescript。如果不

    npm install --save-dev typescript @types/react @types/node.
    

    在 tsconfig.json 中,您应该在编译器选项中包含 "jsx": "preserve"。它允许我们在项目中使用 .tsx 文件。 tsconfig.json 的一个例子

    • 我认为这可能是问题所在。为了表明我们正在返回jsx,我们必须用()包装组件。但是在你的组件中你有

      return <Component {...pageProps} />
      

    即使我试图输入(),vscode 也忽略了它。所以尝试箭头功能:

    const App = ({ Component, pageProps }: AppProps) => (
      <Component {...pageProps} />
    );
    
    export default App;
    

    【讨论】:

    • 打字稿安装正确,因为我创建了这样的项目:yarn create next-app --typescript
    • 你能试试我通过的选项吗?
    • 我试过了但不幸的是得到了同样的错误 :( this 是 IDE 标记错误的方式
    • @ОвовОчоы 我更新了答案。我认为找到了问题
    • 我切换到 @types/react 的 18.0.6 版本并摆脱了错误,无论如何感谢您的帮助!
    【解决方案3】:

    将 devDependencies 中的 React 类型更新为 18(如果你已经使用 17.x):

    "@types/react": "^18",
    "@types/react-dom": "^18"
    

    【讨论】:

      猜你喜欢
      • 2023-01-08
      • 2023-01-31
      • 2021-06-02
      • 2022-06-20
      • 2021-02-20
      • 2021-09-13
      • 1970-01-01
      • 2022-08-22
      • 2022-06-11
      相关资源
      最近更新 更多