我想<html lang="...">用对象表示法在 NextJs 应用程序上设置标签。
我为 Styled-components 渲染了一个 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();
}
}}
Run Code Online (Sandbox Code Playgroud)
我看过很多关于如何渲染常规 JSX 组件的文章,但我想用对象表示法来做。
您可以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>
);
}
}
Run Code Online (Sandbox Code Playgroud)
这是您的完整代码:
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>
);
}
}
Run Code Online (Sandbox Code Playgroud)
更多信息在这里 -链接到文档
所有的
<Html />,<Head />,<Main />和<NextScript />所需要的页面被正确渲染。
| 归档时间: |
|
| 查看次数: |
7166 次 |
| 最近记录: |