Warm tip: This article is reproduced from serverfault.com, please click

javascript-如何通过next.js应用程序使用Google Analytics(分析)?

(javascript - How to use google analytics with next.js app?)

发布于 2020-02-26 10:04:46

我在next.js中使用了样式化组件,因此我的样式需要在服务器端呈现,因此如何向我的网站中添加Google Analytics(分析)?

我检查了next.js谷歌分析示例,但正如我所说的_document文件因使用样式化组件而有所不同。

// _document.js

import React from 'react'
import Document from 'next/document'
import { ServerStyleSheet } from 'styled-components'

class MyDocument extends Document {
  static async getInitialProps(ctx) {
    const sheet = new ServerStyleSheet()
    const originalRenderPage = ctx.renderPage

    try {
      ctx.renderPage = () => originalRenderPage({
        enhanceApp: (App) => (props) => sheet.collectStyles(<App {...props} />),
      })

      const initialProps = await Document.getInitialProps(ctx)
      return {
        ...initialProps,
        styles: (
          <>
            {initialProps.styles}
            {sheet.getStyleElement()}
          </>
        ),
      }
    } finally {
      sheet.seal()
    }
  }
}

export default MyDocument

Questioner
SHAHROOZ
Viewed
11
517 2020-02-26 20:35:34

在你中,_document.js你将覆盖该getInitialProps方法。你也可以覆盖该render方法。只需添加

  render() {
    return (
      <Html lang={this.props.lang || "en"}>
        <Head>
          <script
            dangerouslySetInnerHTML={{
              __html: `[google analytics tracking code here]`
            }}
          />
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }

确保导入所需的组件:

import Document, { Html, Head, Main, NextScript } from "next/document"