我如何将nextjs当前_document.js合并与< head>使用Next/styledComponents的导出默认类代码示例?
按照此处的说明按照说明:为配置样式的components的nextJS,并试图合并当前的
export default function Document() {
return (
<Html>
<Head>
<link href="https://fonts.googleapis.com" rel="preconnect" />
<link crossOrigin href="https://fonts.gstatic.com" rel="preconnect" />
<link
href="https://fonts.googleapis.com/css2?family=Merriweather&family=Newsreader:opsz,[email protected],400;6..72,500&family=Work+Sans:wght@700&display=swap"
rel="stylesheet"
/>
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
_document.js
export default class MyDocument extends Document {
static async getInitialProps(
ctx: DocumentContext
): Promise<DocumentInitialProps> {
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()
}
}
}
What should the combined code look like? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在您的情况下,
导出默认函数文档()
是与类组件的“渲染”部分相对应的函数。在您粘贴的类组件中,渲染方法不会被覆盖。
这意味着您最简单的方法是将所有内容从原始功能移动到类组件中的渲染方法。
这就是外观:
另外,您可以对另一方向进行操作,然后将
getInitialProps
添加到您的功能组件中。为了使您了解这里发生的事情,您可以查找React中类组件和功能组件之间的差异。或阅读这篇冗长的博客文章: https://overreacted.io/如何使用官方组成部分不同类别/
In your case the
export default function Document()
is a function that corresponds to the "render" part of a class Component.And in the class component that you pasted, the render method is not overwritten.
This means the easiest way for you is to move everything from your original function to the render method in the class component.
This is how it would look like:
Alternatively, you could do the other way round and add
getInitialProps
to your function component.In order for you to understand what's going on here, you could look up the differences between class components and function components in React. Or read this lengthy blog post: https://overreacted.io/how-are-function-components-different-from-classes/