如何从Next.js正确键入_document.tsx文件?
我从关于如何使用的官方文档示例中获得了大部分代码styled-components:
https://github.com/vercel/next.js/blob/canary/examples/with-styled-components/pages/_document.js
但是这个例子使用了.js,我正在使用 Typescript。
我收到了一些类型错误和警告,我不确定如何正确输入。我已经解决了部分问题。这是我仍然缺少的:
错误 1:static async getInitialProps(ctx)函数的完整签名类型或返回类型应该是什么?ctx参数的类型是什么?
错误 2:对 的不安全访问ctx.renderPage。我想这将在我正确键入getInitialProps函数后修复
错误 3:这也可能与缺少的类型有关getInitialProps
import React, { ReactElement } from "react";
import Document, { Html, Head, Main, NextScript } from 'next/document';
import { ServerStyleSheet } from "styled-components";
export default 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();
}
}
render(): ReactElement {
return(
<Html lang="en">
<Head>
// SOMETHING IN THE HEAD
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}
回答
这就是我最终为键入getInitialProps和render方法所做的工作:
import React, { ReactElement } from "react";
import Document, { DocumentInitialProps, DocumentContext } from 'next/document';
export default class MyDocument extends Document {
static async getInitialProps(ctx: DocumentContext): Promise<DocumentInitialProps> {
// ...
}
render(): ReactElement {
return(
// ...
);
}
}
https://github.com/vercel/next.js/blob/canary/examples/with-styled-components/pages/_document.js
完整styled-components示例:
import React, { ReactElement } from "react";
import Document, { Html, Head, Main, NextScript, DocumentInitialProps, DocumentContext } from 'next/document';
import { ServerStyleSheet } from "styled-components";
// NEXT.JS CUSTOM DOCUMENT
// https://nextjs.org/docs/advanced-features/custom-document
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(): ReactElement {
return(
<Html lang="en">
<Head>
// SOME HEAD ELEMENTS
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}