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

映射非translation.json来源的数据时如何使用react-i18next实现国际化

实现方案

第一步:调整sidebarData结构,替换硬编码文本为翻译映射key

不需要修改现有translation.json的结构,只需要把sidebarData里的硬编码文本字段替换成和翻译文件对应的key即可,保留icon、path等固定配置项:

const sidebarData = [
  {
    textKey: "sidebarmenu.picken",
    titleKey: "header.picken",
    icon: <GetAppIcon style={{ fontSize: 35 }} />,
    path: "/picken",
  },
  {
    textKey: "sidebarmenu.artikel",
    titleKey: "header.artikel",
    icon: <AddShoppingCartIcon style={{ fontSize: 35 }} />,
    path: "/holeartikel",
  },
  {
    textKey: "sidebarmenu.regal",
    titleKey: "header.regal",
    icon: <ImportExportIcon style={{ fontSize: 35 }} />,
    path: "/holeregal",
  }
];

第二步:修改DrawerComp组件的翻译调用逻辑

直接在组件内用useTranslation返回的t函数,根据key动态拉取对应语言的文本即可,不需要改动其他业务逻辑:

import React, { useState} from "react";
import { useHistory } from "react-router-dom";
import useStyles from "./LayoutStyles";
import { useTranslation } from "react-i18next";
// 补充原代码缺失的ListItemIcon导入
import {Drawer, ListItemIcon, ListItem, List, ListItemText} from "@material-ui/core";

function DrawerComp({ open, setOpen, sidebarData }) {
  const classes = useStyles();
  const history = useHistory();
  const [getPath, setGetPath] useState("Jobliste");
  const { t } = useTranslation();

  function handleClick(item) {
    history.push(item.path);
    // 点击时动态获取对应语言的标题
    setGetPath(t(item.titleKey));
  }

  return (
    <Drawer variant="persistent" anchor="left" open={open}>
      <List className={classes.sbList}>
        {sidebarData.map(item => (
          <ListItem
            key={item.textKey}
            onClick={() => handleClick(item)}
          >
            <ListItemIcon>{item.icon}</ListItemIcon>
            {/* 渲染侧边栏文本时动态翻译 */}
            <ListItemText>{t(item.textKey)}</ListItemText>
          </ListItem>
        ))}
      </List>
    </Drawer>
  );
}

export default DrawerComp;

该方案完全不需要改动现有多语言配置,也不会影响material-ui图标的渲染逻辑,切换语言时i18next会自动更新所有绑定了t函数的文本内容,无需额外做监听处理。

内容的提问来源于stack exchange,提问作者pratibimbam

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 18:57:03