Next.js 使用 _app.js 和 _document.js [英] Next.js use of _app.js and _document.js
问题描述
我目前使用 _document.js
将 css 注入到我的 Next.js 应用程序中,我想开始使用 _app.js
来帮助将数据注入到页面中.
I currently use _document.js
to inject css into my Next.js app and I would like to start using _app.js
to help inject data into pages.
想知道是否可以同时使用 _document 和 _app 还是我们应该只使用一个或另一个?
Was wondering if it possible to use _document and _app in tandem or should we only use one or the other?
推荐答案
简短回答:是的,您可以同时使用两者.它们有不同的用途,可以在同一个应用程序中使用.
Short answer: Yes, You can use both. They serve different purpose and can be used in the same application.
根据nextjs网站:
According to nextjs website:
Next.js 使用 App 组件来初始化页面.
Next.js uses the App component to initialize pages.
要覆盖,请创建 ./pages/_app.js
文件并覆盖 App 类
To override, create the ./pages/_app.js
file and override the App class
和
Next.js 中的页面会跳过周围文档标记的定义.例如,您从不包含 、
等.要覆盖该默认行为,您必须在
./pages 处创建一个文件/_document.js
,在这里可以扩展 Document 类.
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.
注意:_document.js
仅在服务器端呈现,而不在客户端呈现.所以像 onClick
这样的事件处理程序将不起作用.
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.
这篇关于Next.js 使用 _app.js 和 _document.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!