我剛剛使用 npx create-next-app
建立了一個 next.js 13 typescript 應用程式。我已經刪除了所有範例 css 和 html,並嘗試引入 MUI。我的 app/layout.tsx
看起來像這樣:
import { CssBaseline } from '@mui/material'; export default function RootLayout({ children, }: { children: React.ReactNode }) { return ( <html lang="en"> <body> <CssBaseline /> {children} </body> </html> ) }
新增 CSSBaseline
位元會產生一大堆關於 React 匯入中缺少的內容的錯誤。線上閱讀這是因為 React 是從伺服器元件存取的,而根佈局元件必須是該伺服器元件。這是錯誤輸出:
Server Error TypeError: createContext only works in Client Components. Add the "use client" directive at the top of the file to use it. Read more: https://nextjs.org/docs/messages/context-in-server-component This error happened while generating the page. Any console logs will be displayed in the terminal window. Call Stack React node_modules/@emotion/react/dist/emotion-element-6bdfffb2.esm.js (14:41) (sc_server)/./node_modules/@emotion/react/dist/emotion-element-6bdfffb2.esm.js file:///[...]/.next/server/app/page.js (1724:1) __webpack_require__ file:///[...]/.next/server/webpack-runtime.js (33:42) eval webpack-internal:///(sc_server)/./node_modules/@emotion/styled/base/dist/emotion-styled-base.esm.js (8:72) (sc_server)/./node_modules/@emotion/styled/base/dist/emotion-styled-base.esm.js file:///[...]/.next/server/app/page.js (1768:1) __webpack_require__ file:///[...]/.next/server/webpack-runtime.js (33:42) eval webpack-internal:///(sc_server)/./node_modules/@emotion/styled/dist/emotion-styled.esm.js (5:95) (sc_server)/./node_modules/@emotion/styled/dist/emotion-styled.esm.js file:///[...]/.next/server/app/page.js (1779:1) __webpack_require__ file:///[...]/.next/server/webpack-runtime.js (33:42) require node_modules/@mui/styled-engine/node/index.js (46:37)
我不應該這樣做嗎?我錯過了什麼?
我覺得一旦我完成了這項工作,其餘的事情就會落實到位,我將能夠建立我的 MUI 應用程式。
我考慮將material-next-ts範例從頁面路由器移植到應用程式路由器。但是正在使用的情緒版本支援更簡單的預設方法,該方法似乎需要零設置,因此範例中頁面路由跳過的所有環路似乎都是不必要的。如果將範例移植到應用程式路由器,那就太棒了!
P粉1954022922023-12-24 09:29:50
錯誤訊息中的指導將解決該問題:
TypeError: createContext only works in Client Components. Add the "use client" directive at the top of the file to use it. Read more: https://nextjs.org/docs/messages/context-in-server-component
嘗試將 'use client'
指令新增到 app/layout.tsx
的頂部。以下是Next.js 文件關於原因的解釋 '使用客戶端'
是必要的:
這是另一部分解釋您的app/layout.tsx
預設是一個伺服器元件: