Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 静态生成的Next.js页面中的动态HTML lang属性_Reactjs_Next.js - Fatal编程技术网

Reactjs 静态生成的Next.js页面中的动态HTML lang属性

Reactjs 静态生成的Next.js页面中的动态HTML lang属性,reactjs,next.js,Reactjs,Next.js,我正在下一个.Js项目中开发一个多语言静态登录页。 我的目标是拥有以下结构: /->英文主页 /de->德语主页 /it->意大利语主页 我用以下方式构建它: pages/index.js export default function Home() { return <div>English Homepage</div> } 导出默认函数Home(){ 返回英文网页 } 页面/de.js export default function Home() {

我正在下一个.Js项目中开发一个多语言静态登录页。 我的目标是拥有以下结构:

  • /->英文主页
  • /de->德语主页
  • /it->意大利语主页
我用以下方式构建它:

pages/index.js

export default function Home() {
  return <div>English Homepage</div>
}
导出默认函数Home(){
返回英文网页
}
页面/de.js

export default function Home() {
  return <div>German page</div>
}
导出默认函数Home(){
返回德语页
}
为了使网站可访问,我想设置相应的html语言

pages/_document.js

class MyDocument extends Document {
  static async getInitialProps(ctx) {
    const initialProps = await Document.getInitialProps(ctx)
    return { ...initialProps }
  }

  render() {
    return (
      <Html lang={???}>
        <Head />
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    )
  }
}
类MyDocument扩展文档{
静态异步getInitialProps(ctx){
const initialProps=wait Document.getInitialProps(ctx)
返回{…initialProps}
}
render(){
返回(
)
}
}
如何指定每页的语言?
我试过使用
getInitialProps
,但这迫使我的网站成为SSR。

嘿,也许不是最好的解决方案,但应该可以工作,你可以在
\u document.jsx
页面上使用
危险路径
prop,并根据路径决定
语言

render() {
  return (
   <Html lang={this.props.dangerousAsPath === '/de' ? 'de' : 'en'}>
     {/* ... */}
   </Html>
  )
}
render(){
返回(
{/* ... */}
)
}
同样,可能应该有更好的解决方案。干杯

编辑:
如果你可以使用
这个.props.\uu下一个数据页面
直到你找到一个更好的选择。

你确实正确地使用了
getInitialProps
,这与正常页面中禁用自动静态优化的
getInitialProps
不同,
\u document.js
中的
getInitialProps
没有这种效果

这是因为
文档
仅在服务器中呈现<代码>文档
getInitialProps
函数在客户端转换期间,或者在静态优化页面时都不会调用

这就是为什么您可以使用它向页面中注入
lang
prop,并且仍然可以获得静态优化的好处

// _document.js
...
static async getInitialProps(ctx) {
  const initialProps = await Document.getInitialProps(ctx);
  const { pathname } = ctx;
  const lang = pathname.startsWith("/de") ? "de" : "en";
  return { ...initialProps, lang };
}
...
要在客户端转换期间更新
lang
属性,还必须在
\u app.js
中设置一个
useRouter
钩子以观察路由更改:

// _app.js
import React, { useEffect } from "react";
import { useRouter } from "next/router";

export default function MyApp({ Component, pageProps }) {
  const { pathname } = useRouter();
  const lang = pathname.startsWith("/de") ? "de" : "en";
  useEffect(() => {
    document.documentElement.lang = lang;
  }, [lang]);

  return <Component {...pageProps} />;
}
/\u app.js
从“React”导入React,{useffect};
从“下一个/路由器”导入{useRouter};
导出默认函数MyApp({Component,pageProps}){
const{pathname}=useRouter();
const lang=pathname.startsWith(“/de”)?“de”:“en”;
useffect(()=>{
document.documentElement.lang=lang;
},[lang]);
返回;
}
我为您创建了这个代码沙盒作为演示


将其下载到本地计算机并检查代码。在
npm安装之后
,运行
npm运行构建
。您将从构建日志中看到“/”和“de”都是静态的。运行
npm start
并查看页面源代码,您将看到
lang
属性在HTML中设置正确。

对于您的示例,如果您假设URL始终遵循此模式
https://somedomain.com/{lang}/其他一切

然后您可以从url中提取
lang
,如下所示:

class MyDocument extends Document {
  static async getInitialProps(ctx) {
    const initialProps = await Document.getInitialProps(ctx)

    // `ctx.req.path` would be of pattern: `/{lang}/everything-else`
    // ctx.req.path.split('/') --> ['', 'lang', 'everything-else']
    const locale = ctx.req.path.split('/')[1]

    return { ...initialProps, locale }
  }

  render() {
    return (
      // get the language 
      <Html lang={this.props.locale}>
        <Head />
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    )
  }
}
类MyDocument扩展文档{
静态异步getInitialProps(ctx){
const initialProps=wait Document.getInitialProps(ctx)
//`ctx.req.path`的模式为:`/{lang}/其他所有内容`
//ctx.req.path.split('/')-->['''lang','其他所有']
const locale=ctx.req.path.split('/')[1]
返回{…initialProps,locale}
}
render(){
返回(
//了解语言
)
}
}

作为补充说明,我建议探索一下这个包,以获得在next.js中实现本地化的更标准的方法。您找到了如何实现本地化的方法吗?我正试图完成完全相同的事情。汉金德夫,你的建议行得通。唯一的问题是,如果在不重新加载页面的情况下更改页面上的语言,则不会更改html语言属性。我解决这个问题的方法就是刷新关于语言变化的页面。我明白你的意思。我已经使用
useRouter
hook-in
\u app.js
更新了答案和CodeSandbox,以在客户端转换期间更新
lang
属性。