【问题标题】:How to add custom property and extend DocumentInitialProps type in _document?如何在 _document 中添加自定义属性和扩展 DocumentInitialProps 类型?
【发布时间】:2021-12-29 03:07:08
【问题描述】:

我是 Typescript 的初学者。我正在开发 Next.js TypeScript 项目。基本上,我要做的是通过body 标记从服务器端将userCurrency 值传递给客户端。我正在处理_document.tsx 文件。 问题是我收到了这个错误

我从错误消息中收集到的是 userCurrencyDocumentInitialProps 上不存在,并且参考其他 Stack Overflow 帖子,我正在尝试将附加属性 userCurrency 扩展/添加到 DocumentInitialProps

如您所见,我创建了NewDocumentInitialProps。但是,错误仍然存​​在。 我究竟做错了什么?如何向DocumentInitialProps 添加自定义属性?

import { Fragment } from "react";

import Document, {
  DocumentContext,
  Html,
  Head,
  Main,
  NextScript,
  DocumentInitialProps,
} from "next/document";

declare type NewDocumentInitialProps = DocumentInitialProps & {
  userCurrency?: string;
};

export default class CustomDocument extends Document {
  static async getInitialProps(
    ctx: DocumentContext
  ): Promise<NewDocumentInitialProps> {
    const initialProps = await Document.getInitialProps(ctx);
    return {
      ...initialProps,
      ...{ userCurrency: "USD" },
    };
  }

  render(): JSX.Element {
    return (
      <Html>
        <Head>
          {
            <>
              <link rel="icon" href="/favicon_dev.svg" type="image/svg+xml" />
            </>
          }
        </Head>
        <body data-currency={this.props.userCurrency}>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}

【问题讨论】:

  • 请将您的代码粘贴为文本,而不是图像。
  • 在您的第一个代码示例中,您位于一个功能组件中。道具通过函数的第一个参数作为对象传递,而不是 this.props(与类一起使用)。
  • 我已经发布了代码。实际上代码有效,我可以在 DOM 中的 body 标记中看到 this.props.userCurrency 值。抱怨类型的是打字稿编译器。参考第 17 行,上面写着export default class CustomDocument 这是一个功能组件吗?
  • 糟糕,我看错了图片,抱歉。

标签: reactjs typescript next.js


【解决方案1】:

仅仅键入getInitialProps 的返回类型不足以在render 函数中正确键入this.props。在声明类时,您需要将 NewDocumentInitialProps 作为泛型传递给扩展的 Document 类型。

type NewDocumentInitialProps = DocumentInitialProps & {
    userCurrency?: string;
};

export default class CustomDocument extends Document<NewDocumentInitialProps> {
    //...
}

这也将正确键入getInitialProps 的返回类型,因此您不必自己显式地这样做。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-08
    • 1970-01-01
    • 2020-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多