如何在文档组件中的nextjs中获取语言环境?

Joh*_*son 1 next.js

我想在脚本谷歌地图中设置区域设置,如下所示:

<script defer src={`https://maps.googleapis.com/maps/api/js?key=key&libraries=places&language=${locale}`}/>
Run Code Online (Sandbox Code Playgroud)

但我怎样才能到达文档 nextJS 中的区域设置?useRouter 在文档组件中不起作用。

export default function Document() {
  return (
    <Html>
      <Head>
        <link rel="preconnect" href="https://fonts.googleapis.com" />
       
      
<script defer src={`https://maps.googleapis.com/maps/api/js?key=key&libraries=places&language=${locale}`}/> 
      </Head>

      <body>
        <Main />
        <NextScript />
      </body>
    </Html>
  );
}
Run Code Online (Sandbox Code Playgroud)

ryc*_*cha 5

您可以访问 中的区域设置this.props.locale

在我的项目中,该区域设置在这种情况下使用:

 <Html lang={this.props.locale}>
/....
Run Code Online (Sandbox Code Playgroud)

我在 _document 中使用类组件。

在您的变体中,您可以仅在 props 中访问语言环境。

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

export default function Document(props: DocumentProps) {
  return (
    <Html lang={props.locale}>
      <Head />
      <body>
        <Main />
        <NextScript />
      </body>
    </Html>
  );
}

Run Code Online (Sandbox Code Playgroud)

如果您已经添加 i18n 配置并将其注入到下一个配置中,它就可以工作。

https://codesandbox.io/p/sandbox/musing-noether-7loye1?file=%2Fpages%2F_document.tsx&selection=%5B%7B%22endColumn%22%3A9%2C%22endLineNumber%22%3A11%2C%22startColumn% 22%3A9%2C%22startLineNumber%22%3A11%7D%5D