Skip to main content

自定义应用

Next.js 使用 App 组件来初始化页面。你可以覆盖它并控制页面初始化:

¥Next.js uses the App component to initialize pages. You can override it and control the page initialization and:

  • 在页面更改之间创建共享布局

    ¥Create a shared layout between page changes

  • 将附加数据注入页面

    ¥Inject additional data into pages

  • 添加全局 CSS

    ¥Add global CSS

用法

¥Usage

要覆盖默认的 App,请创建文件 pages/_app,如下所示:

¥To override the default App, create the file pages/_app as shown below:

import type { AppProps } from 'next/app'

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

Component 属性是活动的 page,因此每当你在路由之间导航时,Component 都会更改为新的 page。因此,你发送给 Component 的任何属性都会被 page 接收。

¥The Component prop is the active page, so whenever you navigate between routes, Component will change to the new page. Therefore, any props you send to Component will be received by the page.

pageProps 是一个带有初始 props 的对象,由我们的 数据获取方法 之一为你的页面预加载,否则它是一个空对象。

¥pageProps is an object with the initial props that were preloaded for your page by one of our data fetching methods, otherwise it's an empty object.

很高兴知道

¥Good to know

getInitialPropsApp

¥getInitialProps with App

App 中使用 getInitialProps 将禁用没有 getStaticProps 的页面的 自动静态优化

¥Using getInitialProps in App will disable Automatic Static Optimization for pages without getStaticProps.

我们不建议使用此模式。相反,请将 逐步采用 视为应用路由,它允许你更轻松地获取 页面和布局 的数据。

¥We do not recommend using this pattern. Instead, consider incrementally adopting the App Router, which allows you to more easily fetch data for pages and layouts.

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' }
}
import App from 'next/app'

export default function MyApp({ Component, pageProps, example }) {
return (
<>
<p>Data: {example}</p>
<Component {...pageProps} />
</>
)
}

MyApp.getInitialProps = async (context) => {
const ctx = await App.getInitialProps(context)

return { ...ctx, example: 'data' }
}