自定义 App 组件
Next.js 使用 App
组件来初始化页面。你可以覆盖它并控制页面初始化,实现以下功能:
- 在页面切换时创建共享布局
- 向页面注入额外数据
- 添加全局 CSS
使用方法
要覆盖默认的 App
组件,请按以下方式创建 pages/_app
文件:
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
的任何属性都会被页面接收。
pageProps
是一个对象,包含通过 数据获取方法 为页面预加载的初始属性,如果没有预加载则为空对象。
须知:
- 如果应用正在运行且你添加了自定义
App
组件,需要重启开发服务器(仅当原先不存在pages/_app.js
时需要)App
组件不支持 Next.js 的 数据获取方法,如getStaticProps
或getServerSideProps
在 App
中使用 getInitialProps
在 App
组件中使用 getInitialProps
会禁用没有 getStaticProps
的页面的 自动静态优化。
我们不推荐使用这种模式。建议考虑 渐进式迁移 到 App Router,这样可以更轻松地为页面和布局获取数据。
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' }
}