【问题标题】:React internalisation SPA using i18next使用 i18next 反应内部化 SPA
【发布时间】:2023-05-16 13:14:01
【问题描述】:

我需要翻译我的应用程序,但我不知道如何在*文件中使用 useTranslation()(我在那里存储了一些包含一些文本的常量)。该文件之一是

import { useTranslation } from "react-i18next";

const {t} = useTranslation()

    export const selectThemeOptions = [
      { value: "choose", text: "Choose theme" },
      { value: "Algebra", text: "Algebra" },
      { value: "Geometry", text: "Geomerty" },
      { value: "Programming", text: "Programming" },
      { value: "Logic", text: "Logic" },
    ];

所以在这种情况下我有一个错误: src\Configs\ThemesOfProblems.js 第 3:13 行:无法在顶层调用 React Hook “useTranslation”。 React Hooks 必须在 React 函数组件或自定义 React Hook 函数 react-hooks/rules-of-hooks 中调用

我的组件中需要这个数组,并在下一个片段中使用:

<Form.Group as={Col} controlId="problemTheme">
                                <Form.Label>{t("userprofile.theme")}</Form.Label>
                                <Form.Select
                                    name="theme"
                                    value={values.theme}
                                    onChange={handleChange}
                                    isValid={touched.theme && !errors.theme}
                                    isInvalid={!!errors.theme}
                                    onBlur={handleBlur}
                                >
                                    {selectThemeOptions.map((el, index) => {
                                        return <option key={index} value={el.value}> {el.text} </option>
                                    })}
                                </Form.Select>
                            </Form.Group>

我遇到过很多这样的情况,我不知道该怎么做

【问题讨论】:

    标签: javascript reactjs react-native internationalization i18next


    【解决方案1】:

    基本上它说它必须在反应组件中调用。它可以在返回 jsx 的功能组件中调用,也可以在其中包含 render 方法的类组件中调用。如果您在其中之一之外调用该函数,则会收到此错误。

    【讨论】:

    • 我知道,但是如何从组件中调用它
    • 我能提供的唯一解决方案是在组件中调用它,然后将其作为参数发送。
    【解决方案2】:

    您在 React 组件之外调用了 const {t} = useTranslation();,由于缺少 JSX 或 HTML 的返回语句,您的 selectThemeOptions 文件似乎是常规的 JavaScript

    以下是正确的做法:

    /* Everything above this point is considered top-level, hence using your `useTranslation()` hook here would cause an error */
    
    const Component = (props) => {
      const { t } = useTranslation();
    }
    
    export default Component;
    

    这是一种组织翻译的方法:

    • 您的src 文件夹应包含一个带有以下代码的i18n.js 文件:

    import i18n from "i18next";
    import { initReactI18next } from "react-i18next";
    import en from "../locales/en.json";
    import ru from "../locales/ru.json";
    
    const isReturningUser = "lang" in localStorage; // Returns true if user already used the website.
    const savedLanguage = JSON.parse(localStorage.getItem("lang")); // Gets persisted language from previous visit.
    
    // Get previously used language in case of returning user or set language to Russian by default.
    const language = isReturningUser ? savedLanguage : "ru";
    
    const resources = {
      en: {
        translation: en,
      },
      ru: {
        translation: ru,
      },
    };
    
    i18n.use(initReactI18next).init({
      resources,
      lng: language,
      keyseparator: false,
      interpolation: {
        escapeValue: false,
      },
    });
    
    export default i18n;
    
    • 您的src 文件夹应包含一个locales 文件夹,其中包含您的应用程序使用的语言的json 文件。示例:ru.jsonen.json
    {
      "choose": "Выбрать",
      "chooseATheme": "Выбрать тему",
      "algebra": "Алгебра",
      "geometry": "Геометрия",
      "programming": "Программирование",
      "logic": "Логика",
    }
    
    
    • 您的组件应如下所示 - 请注意,翻译位于 json 文件中,而不是您的 React 组件中 - :
    import React from "react";
    import { useTranslation } from "react-i18next";
    
    const Component = (props) => {
      const { t } = useTranslation();
    
    const selectThemeOptions = [
          { value: t("choose"), text: t("chooseATheme") },
          { value: t("algebra"), text: t("algebra") },
          { value: t("geometry"), text: t("geometry") },
          { value: t("programming"), text: t("programming") },
          { value: t("logic"), text: t("logic") },
        ];
    
    return( //Your UI )
       
    }
    
    export default Component;
    

    这样,您的翻译不会在您的 selectThemeOptions 上硬编码,并且会适应您的 json 语言环境包含的任何翻译。

    请告诉我这是否有效。

    编辑:如果您想在这里实现我的解决方案的具体示例:https://github.com/YHADJRABIA/ecommerce/tree/main/src

    Edit2:这样做可能有更好的解决方案,这只是对我有用。

    Edit3:根据 Nikita 的评论,这是在 react 组件之外使用翻译功能的解决方案 —How to use react-i18next inside BASIC function (not component)?

    附:由于您来自白俄罗斯,我假设您希望您的翻译用俄语进行,因为白俄罗斯语的使用并不广泛。

    【讨论】:

    • 我有很多文件存储文本、表格列的配置、是的文本字段等等,所以我知道我现在不能拥有这些文件(
    • 好吧,所以如果我理解正确,你唯一关心的就是让 useTranslation() 钩子在非 React 组件中工作。我会试着弄清楚这一点并回信。编辑:这是我发现的:*.com/questions/57864069/…
    • 我编辑了我的原始帖子,其中包含可能有助于解决您的问题的链接。