我在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
在你中,_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"