乐闻世界logo
搜索文章和话题

Nextjs 项目中如何使用 _app.js 和 _document.js ?

7 个月前提问
3 个月前修改
浏览次数145

2个答案

1
2

在Next.js中,_app.js_document.js 文件是对Next.js应用程序的默认结构和行为进行自定义的两个特殊文件。

_app.js

_app.js 文件用于初始化所有页面。你可以使用这个文件来保持页面布局,或者保持页面的状态(如登录状态)时跨页面保持一致。还可以用来添加全局CSS样式。

当你创建自定义的_app.js,你需要导出一个React组件来接收一些特定的props,比如ComponentpagePropsComponent prop是你的页面内容,而pageProps是一个对象,包含了你能用来初始化页面的props。

例如,如果你想要所有页面都包含同一导航栏和页脚,你可以这样做:

jsx
import React from 'react'; import Navbar from '../components/Navbar'; import Footer from '../components/Footer'; // 这里的Component是当前页面 function MyApp({ Component, pageProps }) { return ( <> <Navbar /> <main> <Component {...pageProps} /> </main> <Footer /> </> ); } export default MyApp;

_document.js

_document.js 文件允许你自定义<html><body>标签以及文档的结构。这个文件只会在服务器端渲染时运行,因此不要在这里添加应用程序逻辑。

_document.js 用于更改服务端渲染的文档内容。这通常是需要添加服务端渲染的代码片段(比如自定义字体或者<meta>标签),或者当你需要为<html><body>标签添加额外的属性时。

一个自定义的_document.js看起来是这样的:

jsx
import Document, { Html, Head, Main, NextScript } from 'next/document'; class MyDocument extends Document { render() { return ( <Html lang="en"> <Head> {/* 这里放置 `<link>` 或 `<meta>` 标签 */} </Head> <body> {/* 这里可以添加额外的元素到body中,但通常你只需要 */} <Main /> {/* <-- 这里渲染应用内容 */} <NextScript /> {/* <-- 这里渲染Next.js脚本 */} </body> </Html> ); } } export default MyDocument;

_document.js中,<Main />组件会被替换为你的应用页面内容,而<NextScript />是用于Next.js的核心脚本,是必须包含的。

总结

  • 使用_app.js来添加布局组件或全局状态管理(如Redux或Context API)。
  • 使用_document.js来定制服务端渲染的文档结构和标签,例如添加自定义字体、统计代码或对<html><body>标签的附加属性。

请注意,这两个文件都是可选的,如果你的应用不需要对默认行为作出任何修改,你完全可以不添加它们。

2024年6月29日 12:07 回复

Short answer: Yes, You can use both. They serve different purpose and can be used in the same application.

According to NextJS docs:

Next.js uses the App component to initialize pages.

To override, create the ./pages/_app.js file and override the App class

and

Pages in Next.js skip the definition of the surrounding document's markup. For example, you never include <html>, <body>, etc. To override that default behavior, you must create a file at ./pages/_document.js, where you can extend the Document class.

Note: _document.js is only rendered on the server side and not on the client side. so event handlers like onClick is not going to work.

2024年6月29日 12:07 回复

你的答案