如何将 NextJS 当前_document.js与从<Head>下一个/样式组件示例中导出默认类代码合并?



按照下面的说明:https://medium.com/nerd-for-tech/using-next-js-with-styled-components-easy-dfff3849e4f1为有样式的组件配置nextJS,并试图合并当前的_document.js

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,wght@6..72,400;6..72,500&family=Work+Sans:wght@700&display=swap"
rel="stylesheet"
/>
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
); 

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.

在您的案例中,export default function Document()是一个对应于"render"Component.

并且在您粘贴的类组件中,渲染方法不会被覆盖。

这意味着对您来说最简单的方法是将所有内容从原始函数移到类组件中的呈现方法中。

应该是这样的:

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();
}
}
render() {
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,wght@6..72,400;6..72,500&family=Work+Sans:wght@700&display=swap"
rel="stylesheet"
/>
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}

或者,您可以反过来做,并将getInitialProps添加到您的函数组件。

为了让你理解这里发生了什么,你可以在React中查找类组件和函数组件之间的区别。或者阅读这篇冗长的博文:https://overreacted.io/how-are-function-components-different-from-classes/

最新更新