使用NextJs 13设置react-i18next以进行组件本地化时出现问题

问题描述 投票:0回答:1

我正在深入研究 NextJS 13,我需要了解 i18next 的一个简单用例:

我的目标只是翻译服务器端和客户端的组件,就像这样简单:

import { withTranslation } from 'react-i18next';

const MyComponent  = () => {
  return <p>{t('msg')}</p>
}


export default MyComponent;

我正在使用新的应用程序路由机制,我需要具有以下目录结构:

app
 |------ about
 |------ home
components
 |------- MyComponent
locale
 |------- en
 |        |---- MyComponent.json
 |------- de
 |        |---- MyComponent.json
    

基本上我想将字典文件保留在语言环境文件夹中,并且不想使用

app->[lang]->page
模式。

可以使用 NextJS 13 来完成吗? 使用 NextJs 13,我是否受到

app->[lang]->page
结构的束缚?

好吧,为了继续前进并边做边学,我已经安装了react-i18next 和i18next 并尝试设置一个简单的项目:

我的 i18n.js 配置:

import i18n from "i18next";
import { initReactI18next } from "react-i18next";

// the translations
// (tip move them in a JSON file and import them,
// or even better, manage them separated from your code: https://react.i18next.com/guides/multiple-translation-files)
const resources = {
  en: {
    translation: {
      "msg": "Welcome to React and react-i18next"
    }
  },
  fr: {
    translation: {
      "msg": "Bienvenue à React et react-i18next"
    }
  }
};

i18n
  .use(initReactI18next) // passes i18n down to react-i18next
  .init({
    resources,
    lng: "en", // language to use, more information here: https://www.i18next.com/overview/configuration-options#languages-namespaces-resources
    // you can use the i18n.changeLanguage function to change the language manually: https://www.i18next.com/overview/api#changelanguage
    // if you're using a language detector, do not define the lng option

    interpolation: {
      escapeValue: false // react already safes from xss
    }
  });

  export default i18n;

运行时出现以下错误:

./src/app/i18n.js
ReactServerComponentsError:

You're importing a component that needs createContext. It only works in a Client Component but none of its parents are marked with "use client", so they're Server Components by default.

   ,-[/Users/mnd/dev/node_modules/react-i18next/dist/es/context.js:1:1]
 1 | import { createContext } from 'react';
   :          ^^^^^^^^^^^^^
 2 | import { getDefaults, setDefaults } from './defaults.js';
 3 | import { getI18n, setI18n } from './i18nInstance.js';
 4 | import { initReactI18next } from './initReactI18next.js';
   `----

The error was caused by importing 'react-i18next/dist/es/index.js' in './src/app/i18n.js'.

Maybe one of these should be marked as a client entry with "use client":
  ./src/app/i18n.js
  ./src/app/page.tsx

我完全不知道该从哪里开始......不确定,但由于服务器组件的原因,NextJs 13 不支持

context
。如果没有,我怎样才能按照我需要的方式使用react-i18next?

reactjs next.js i18next nextjs13 react-i18next
1个回答
0
投票

您必须更改 i18n.js 配置导入

import { initReactI18next } from "react-i18next";

import { initReactI18next } from "react-i18next/initReactI18next";
© www.soinside.com 2019 - 2024. All rights reserved.