You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React i18next如何在顶层常量文件中使用useTranslation实现国际化

错误原因

React Hook 只能在函数组件或自定义 Hook 的内部调用,你在常量文件顶层直接调用useTranslation违反了Hook规则,所以触发了报错。可根据你的场景选择以下任意一种方案解决:


方案1:将静态常量改造为接收翻译函数的工厂函数

改造成本最低,不需要调整现有渲染逻辑,完全符合Hook规则:

// ThemesOfProblems.js 改造后
export const getSelectThemeOptions = (t) => [
  { value: "choose", text: t("theme.choose") },
  { value: "Algebra", text: t("theme.algebra") },
  { value: "Geometry", text: t("theme.geometry") },
  { value: "Programming", text: t("theme.programming") },
  { value: "Logic", text: t("theme.logic") },
];

在使用的组件中,先拿到翻译函数再调用工厂函数获取选项:

// 组件内部
const { t } = useTranslation();
const selectThemeOptions = getSelectThemeOptions(t);

// 后续渲染逻辑和你之前的代码完全一致,无需修改

方案2:封装为自定义Hook实现复用

如果这个选项数组需要在多个组件中使用,可以直接封装为自定义Hook,内部可正常调用useTranslation,切换语言时会自动更新翻译内容:

// ThemesOfProblems.js 改造后
import { useTranslation } from "react-i18next";

export const useThemeOptions = () => {
  const { t } = useTranslation();
  return [
    { value: "choose", text: t("theme.choose") },
    { value: "Algebra", text: t("theme.algebra") },
    { value: "Geometry", text: t("theme.geometry") },
    { value: "Programming", text: t("theme.programming") },
    { value: "Logic", text: t("theme.logic") },
  ];
};

组件中直接调用Hook即可使用:

const selectThemeOptions = useThemeOptions();

方案3:直接调用i18n全局实例(无需Hook)

如果不想调整现有常量的结构,可以直接导入你初始化完成的i18n实例调用翻译方法,不受Hook规则限制:

// ThemesOfProblems.js 改造后
import i18n from 'i18next'; // 导入你项目中已经初始化完成的i18n实例

export const selectThemeOptions = [
  { value: "choose", text: i18n.t("theme.choose") },
  { value: "Algebra", text: i18n.t("theme.algebra") },
  { value: "Geometry", text: i18n.t("theme.geometry") },
  { value: "Programming", text: i18n.t("theme.programming") },
  { value: "Logic", text: i18n.t("theme.logic") },
];

注意:该方案切换语言时不会自动更新翻译,需要手动触发组件重渲染才会刷新文本,适合不需要动态切换语言的场景。


内容的提问来源于stack exchange,提问作者Никита Шапаренко

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 17:54:04