跳到主要內容

自訂 App

Next.js 使用 App 元件來初始化頁面。您可以覆寫它並控制頁面初始化和

  • 在頁面變更之間建立共用版面配置
  • 將額外資料注入到頁面中
  • 新增全域 CSS

用法

若要覆寫預設的 App,請建立 pages/_app 檔案,如下所示

pages/_app.tsx
import type { AppProps } from 'next/app'
 
export default function MyApp({ Component, pageProps }: AppProps) {
  return <Component {...pageProps} />
}

Component prop 是作用中的 page,因此每當您在路由之間導航時,Component 都會變更為新的 page。因此,您傳送給 Component 的任何 props 都會由 page 接收。

pageProps 是一個物件,其中包含由我們的資料抓取方法之一為您的頁面預先載入的初始 props,否則它會是空物件。

要知道的是:

  • 如果您的應用程式正在執行,而且您新增了自訂 App,則您需要重新啟動開發伺服器。只有在 pages/_app.js 之前不存在時才需要。
  • App 不支援 Next.js 資料抓取方法,例如 getStaticPropsgetServerSideProps

getInitialPropsApp

App 中使用 getInitialProps 將會停用沒有 getStaticProps 的頁面的自動靜態最佳化

我們不建議使用此模式。 請考慮逐步採用 App Router,這可讓您更輕鬆地為頁面和版面配置抓取資料。

pages/_app.tsx
import App, { AppContext, AppInitialProps, AppProps } from 'next/app'
 
type AppOwnProps = { example: string }
 
export default function MyApp({
  Component,
  pageProps,
  example,
}: AppProps & AppOwnProps) {
  return (
    <>
      <p>Data: {example}</p>
      <Component {...pageProps} />
    </>
  )
}
 
MyApp.getInitialProps = async (
  context: AppContext
): Promise<AppOwnProps & AppInitialProps> => {
  const ctx = await App.getInitialProps(context)
 
  return { ...ctx, example: 'data' }
}