当前位置: 首页 > 文档资料 > Next.js 中文文档 >

自定义 <Document>

优质
小牛编辑
118浏览
2023-12-01

Examples
  • Styled components custom document
  • Google AMP

解释

  • 在服务端呈现
  • 初始化服务端时添加文档标记元素
  • 通常实现服务端渲染会使用一些 css-in-js 库,如styled-components, glamorous 或 emotion。styled-jsx是 Next.js 自带默认使用的 css-in-js 库

Next.js会自动定义文档标记,比如,你从来不需要添加<html>, <body>等。如果想自定义文档标记,你可以新建./pages/_document.js,然后扩展Document类:

// _document is only rendered on the server side and not on the client side
// Event handlers like onClick can't be added to this file

// ./pages/_document.js
import Document, { Head, Main, NextScript } from 'next/document'

export default class MyDocument extends Document {
  static async getInitialProps(ctx) {
    const initialProps = await Document.getInitialProps(ctx)
    return { ...initialProps }
  }

  render() {
    return (
      <html>
        <Head>
          <style>{`body { margin: 0 } /* custom! */`}</style>
        </Head>
        <body className="custom_class">
          <Main />
          <NextScript />
        </body>
      </html>
    )
  }
}

钩子getInitialProps接收到的参数ctx对象都是一样的

  • 回调函数renderPage是会执行 React 渲染逻辑的函数(同步),这种做法有助于此函数支持一些类似于 Aphrodite 的 renderStatic 等一些服务器端渲染容器。

注意:<Main />外的 React 组件将不会渲染到浏览器中,所以那添加应用逻辑代码。如果你页面需要公共组件(菜单或工具栏),可以参照上面说的App组件代替。