我想在具有对象符号的NextJs应用程序上设置<html lang="...">
标签。
我正在渲染样式组件的serverStylesheet,因此我当前的_document
文件如下所示:
class CustomDocument extends Document {
static getInitialProps = async (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();
}
}}
我看过很多关于如何渲染常规JSX组件的文章,但是我想用对象符号来实现。
答案 0 :(得分:3)
您可以从该类中返回自定义render()
,这将允许您使用所需的<html>
属性来装饰lang
。
import Document, { Html, Head, Main, NextScript } from "next/document";
export default class CustomDocument extends Document {
static async getInitialProps(ctx) {
...
}
render() {
return (
<Html lang="en">
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}
这是您的完整代码:
import Document, { Html, Head, Main, NextScript } from "next/document";
import { ServerStyleSheet } from "styled-components";
export default class CustomDocument 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();
}
}
render() {
return (
<Html lang="en">
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}
此处有更多信息-Link to docs
要正确渲染页面,必须使用
<Html />
,<Head />
,<Main />
和<NextScript />
中的所有内容。