如何在 next.js 应用程序中使用谷歌分析? [英] How to use google analytics with next.js app?
本文介绍了如何在 next.js 应用程序中使用谷歌分析?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 next.js 中使用了样式组件,因此我的样式需要在服务器端呈现,因此我如何将 google 分析添加到我的网站?
I'm using styled-components with next.js so my styles need to be server-side rendered, hence how can I add google analytics to my website?
我检查了 next.js 谷歌分析示例 但正如我所说,由于使用了样式组件,我的 _document 文件有所不同.
I checked next.js google analytics example but as I said my _document file is different because of using styled-components.
// _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
推荐答案
在您的 _document.js
中,您覆盖了 getInitialProps
方法.您还可以覆盖 render
方法.只需添加
In your _document.js
you override the getInitialProps
method. You can also override the render
method. Simply add
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"
这篇关于如何在 next.js 应用程序中使用谷歌分析?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文