如何在你的ReactJS应用中使用i18next进行本地化

573 阅读2分钟

在这篇文章中,我们要做的是国际化。我们将使我们的reactJS应用程序具有长期的可扩展性,并研究如何将其带入,无论它是你新创建的应用程序还是你已经维护了一段时间的应用程序。

为什么是国际化?

这是一个设计和开发你的应用程序或产品的想法,你可以为不同的受众实现本地化,因为你的终端用户可能来自不同的文化,来自许多地区和文化。因此,重要的是要以这样的方式进行你的应用程序,如果你必须引入本地化,它不会给你带来很多问题。

使用 react-i18next 进行本地化

在本指南中,我们将使用**node包react-i18next。我们将把我们的i18next配置**设置在 配置目录下:

import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import LanguageDetector from "i18next-browser-languagedetector";

i18n
  // here we are going to detect users default browser language
  .use(LanguageDetector)

  // here we pass our i18n instance
  .use(initReactI18next)

  //initialization step
  .init({
    debug: true,

    // fallback language in case language is not detected
    fallbackLng: "en",

    interpolation: {
      escapeValue: false,
    },

    resources: {
      en: {
        translation: {
          // here we will keep our translations for different languages
        },
      },
    },
  });

并调用它,这样它就可以和我们的整个应用捆绑在一起。现在我们可以通过以下方式进行翻译:

  • 通过使用Trans组件包装器
  • 通过使用useTranslation 挂钩

现在我更喜欢使用Translation,因为它可以更干净地注入到你的代码中,而且更容易阅读。让我们看看它的操作。我将翻译我的文本输入中的占位符。我为实现这一目标所做的调整是

import { useTranslation } from "react-i18next";
import { StyledPlanetInput } from "./styled/PlanetInput.styled";

export default function PlanetInput({ newPlanetInput, handleAddPlanet }) {
  const { t } = useTranslation();
  return (
    <StyledPlanetInput>
      <input
        className="planet-input"
        ref={newPlanetInput}
        type="text"
        placeholder={t("createPlanet")}
      />
      <button className="planet-submit" onClick={handleAddPlanet}>
        +
      </button>
    </StyledPlanetInput>
  );
}

我使用了翻译钩子并调用了在配置中设置的语言资源。现在将语言添加到配置中。

resources: {
  en: {
    translation: {
      planet: "Planet",
      createPlanet: "Create a new planet",
      // here we will keep our translations for different languages
    },
  },
  de: {
    translation: {
      planet: "Planeten",
      createPlanet: "Erstellen Sie einen neuen Planeten",
    },
  },
},

我在我的应用程序中添加了德语作为我的第二语言选项,为了让用户能够在应用程序中选择语言,我们可以这样做

const languages = {
  en: { nativeName: "English" },
  de: { nativeName: "Deutsch" },
};

function YourComponent {
 return (
   // ... rest of your component

    // place where you want to place the buttons
    {Object.keys(languages).map((langauge) => (
      <button
        key={langauge}
        style={{
          fontWeight:
           i18next.resolvedLanguage === langauge ? "bold" : "normal",
        }}
        type="submit"
        onClick={() => i18next.changeLanguage(langauge)}
      >
        {languages[langauge].nativeName}
      </button>
    ))}

   // ... rest of your component
 )
}

你也可以使用**npm包i18next-browser-languagedetector**自动选择用户的默认浏览器语言。

你的叔叔🥳

BOOOOOOOMMM🚀

总结

现在你可以添加任何你想要的语言,你的应用程序将完美地支持它。如果你不对你的字符串进行硬编码,这对你来说可能会更容易😜 。无论如何,这是为了继续良好的编码实践,并在下一次见。不是告别。