Ово*_*чоы 7 javascript typescript reactjs next.js
这是 _app.tsx 的样子:
function MyApp({ Component, pageProps }: AppProps) {
return <Component {...pageProps} />
}
Run Code Online (Sandbox Code Playgroud)
我在构建项目时收到此错误:
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'.
Run Code Online (Sandbox Code Playgroud)
这些是反应版本:
"react": "17.0.2",
"react-dom": "17.0.2",
"@types/react": "17.0.26",
Run Code Online (Sandbox Code Playgroud)
我尝试切换到 18 版本,它有效,但是我收到此错误:Hydration failed because the initial UI does not match what was rendered on the server
将以下代码添加到package.json文件中
"resolutions": {
"@types/react": "17.0.2",
"@types/react-dom": "17.0.2"
}
Run Code Online (Sandbox Code Playgroud)
然后重新安装软件包
yarn
Run Code Online (Sandbox Code Playgroud)
npm i
Run Code Online (Sandbox Code Playgroud)
我认为这是因为你没有在你的项目中正确设置打字稿。我认为,目前,当您安装 next.js 时,您应该可以选择选择typescript。如果不
npm install --save-dev typescript @types/react @types/node.
Run Code Online (Sandbox Code Playgroud)
在 tsconfig.json 中,您应该有 "jsx": "preserve"编译器选项。它允许我们在项目中使用 .tsx 文件。tsconfig.json 的示例
我想这可能就是问题所在。为了表明我们正在返回,jsx我们必须用 包裹组件()。但在你的组件中你有
return <Component {...pageProps} />
Run Code Online (Sandbox Code Playgroud)
即使我尝试放入(),vscode 也会忽略它。所以尝试箭头函数:
const App = ({ Component, pageProps }: AppProps) => (
<Component {...pageProps} />
);
export default App;
Run Code Online (Sandbox Code Playgroud)