Reactjs 如何在routes.js文件中实现react-i18next

Reactjs 如何在routes.js文件中实现react-i18next,reactjs,i18next,Reactjs,I18next,我有一个左侧导航栏,它使用我的admin.js文件。这进而导入my routes.js文件,该文件返回一个带有数组的常量。在不违反“挂钩”规则的情况下,是否可以使用react-i18next以任何方式翻译这些项目 请注意,我已经在我的内容页上实现了react-i18next,它们工作得很好。不包括以下代码中的任何react-i18next导入 我的Admin.js文件 import React from "react"; import cx from "classnames"; import {

我有一个左侧导航栏,它使用我的admin.js文件。这进而导入my routes.js文件,该文件返回一个带有数组的常量。在不违反“挂钩”规则的情况下,是否可以使用react-i18next以任何方式翻译这些项目

请注意,我已经在我的内容页上实现了react-i18next,它们工作得很好。不包括以下代码中的任何react-i18next导入

我的Admin.js文件

import React from "react";
import cx from "classnames";
import { Switch, Route, Redirect } from "react-router-dom";
// creates a beautiful scrollbar
import PerfectScrollbar from "perfect-scrollbar";
import "perfect-scrollbar/css/perfect-scrollbar.css";

// @material-ui/core components
import { makeStyles } from "@material-ui/core/styles";

// core components
import AdminNavbar from "components/Navbars/AdminNavbar.js";
import Footer from "components/Footer/Footer.js";
import Sidebar from "components/Sidebar/Sidebar.js";
import FixedPlugin from "components/FixedPlugin/FixedPlugin.js";

import routes from "routes.js";

import styles from "assets/jss/material-dashboard-pro-react/layouts/adminStyle.js";

var ps;

const useStyles = makeStyles(styles);

export default function Dashboard(props) {
  const { ...rest } = props;
  // states and functions
  const [mobileOpen, setMobileOpen] = React.useState(false);
  const [miniActive, setMiniActive] = React.useState(false);
  const [image, setImage] = React.useState(require("assets/img/sidebar-2.jpg"));
  const [color, setColor] = React.useState("blue");
  const [bgColor, setBgColor] = React.useState("black");
  // const [hasImage, setHasImage] = React.useState(true);
  const [fixedClasses, setFixedClasses] = React.useState("dropdown");
  const [logo, setLogo] = React.useState(require("assets/img/logo-white.svg"));
  // styles
  const classes = useStyles();
  const mainPanelClasses =
    classes.mainPanel +
    " " +
    cx({
      [classes.mainPanelSidebarMini]: miniActive,
      [classes.mainPanelWithPerfectScrollbar]:
        navigator.platform.indexOf("Win") > -1
    });
  // ref for main panel div
  const mainPanel = React.createRef();
  // effect instead of componentDidMount, componentDidUpdate and componentWillUnmount
  React.useEffect(() => {
    if (navigator.platform.indexOf("Win") > -1) {
      ps = new PerfectScrollbar(mainPanel.current, {
        suppressScrollX: true,
        suppressScrollY: false
      });
      document.body.style.overflow = "hidden";
    }
    window.addEventListener("resize", resizeFunction);

    // Specify how to clean up after this effect:
    return function cleanup() {
      if (navigator.platform.indexOf("Win") > -1) {
        ps.destroy();
      }
      window.removeEventListener("resize", resizeFunction);
    };
  });
  // functions for changeing the states from components
  const handleImageClick = image => {
    setImage(image);
  };
  const handleColorClick = color => {
    setColor(color);
  };
  const handleBgColorClick = bgColor => {
    switch (bgColor) {
      case "white":
        setLogo(require("assets/img/logo.svg"));
        break;
      default:
        setLogo(require("assets/img/logo-white.svg"));
        break;
    }
    setBgColor(bgColor);
  };
  const handleFixedClick = () => {
    if (fixedClasses === "dropdown") {
      setFixedClasses("dropdown show");
    } else {
      setFixedClasses("dropdown");
    }
  };
  const handleDrawerToggle = () => {
    setMobileOpen(!mobileOpen);
  };
  const getRoute = () => {
    return window.location.pathname !== "/admin/full-screen-maps";
  };
  const getActiveRoute = routes => {
    let activeRoute = "Default Brand Text";
    for (let i = 0; i < routes.length; i++) {
      if (routes[i].collapse) {
        let collapseActiveRoute = getActiveRoute(routes[i].views);
        if (collapseActiveRoute !== activeRoute) {
          return collapseActiveRoute;
        }
      } else {
        if (
          window.location.href.indexOf(routes[i].layout + routes[i].path) !== -1
        ) {
          return routes[i].name;
        }
      }
    }
    return activeRoute;
  };
  const getRoutes = routes => {
    return routes.map((prop, key) => {
      if (prop.collapse) {
        return getRoutes(prop.views);
      }
      if (prop.layout === "/admin") {
        return (
          <Route
            path={prop.layout + prop.path}
            component={prop.component}
            key={key}
          />
        );
      } else {
        return null;
      }
    });
  };
  const sidebarMinimize = () => {
    setMiniActive(!miniActive);
  };
  const resizeFunction = () => {
    if (window.innerWidth >= 960) {
      setMobileOpen(false);
    }
  };

  return (
    <div className={classes.wrapper}>
      <Sidebar
        routes={routes}
        logoText={"My App"}
        logo={logo}
        image={image}
        handleDrawerToggle={handleDrawerToggle}
        open={mobileOpen}
        color={color}
        bgColor={bgColor}
        miniActive={miniActive}
        {...rest}
      />
      <div className={mainPanelClasses} ref={mainPanel}>
        <AdminNavbar
          sidebarMinimize={sidebarMinimize.bind(this)}
          miniActive={miniActive}
          brandText={getActiveRoute(routes)}
          handleDrawerToggle={handleDrawerToggle}
          {...rest}
        />
        {/* On the /maps/full-screen-maps route we want the map to be on full screen - this is not possible if the content and conatiner classes are present because they have some paddings which would make the map smaller */}
        {getRoute() ? (
          <div className={classes.content}>
            <div className={classes.container}>
              <Switch>
                {getRoutes(routes)}
                <Redirect from="/admin" to="/admin/dashboard" />
              </Switch>
            </div>
          </div>
        ) : (
          <div className={classes.map}>
            <Switch>
              {getRoutes(routes)}
              <Redirect from="/admin" to="/admin/dashboard" />
            </Switch>
          </div>
        )}
        {getRoute() ? <Footer fluid /> : null}
        <FixedPlugin
          handleImageClick={handleImageClick}
          handleColorClick={handleColorClick}
          handleBgColorClick={handleBgColorClick}
          color={color}
          bgColor={bgColor}
          bgImage={image}
          handleFixedClick={handleFixedClick}
          fixedClasses={fixedClasses}
          sidebarMinimize={sidebarMinimize.bind(this)}
          miniActive={miniActive}
        />
      </div>
    </div>
  );
}
从“React”导入React;
从“类名称”导入cx;
从“react router dom”导入{交换机、路由、重定向};
//创建一个漂亮的滚动条
从“完美滚动条”导入PerfectScrollbar;
导入“perfect scrollbar/css/perfect scrollbar.css”;
//@material ui/核心组件
从“@material ui/core/styles”导入{makeStyles}”;
//核心部件
从“components/Navbars/AdminNavbar.js”导入AdminNavbar;
从“components/Footer/Footer.js”导入页脚;
从“components/Sidebar/Sidebar.js”导入侧栏;
从“components/FixedPlugin/FixedPlugin.js”导入FixedPlugin;
从“routes.js”导入路由;
从“assets/jss/material dashboard pro react/layouts/adminStyle.js”导入样式;
var-ps;
const useStyles=生成样式(样式);
导出默认功能仪表板(道具){
const{…rest}=props;
//状态和功能
const[mobileOpen,setMobileOpen]=React.useState(false);
const[miniActive,setMiniActive]=React.useState(false);
const[image,setImage]=React.useState(require(“assets/img/sidebar-2.jpg”);
const[color,setColor]=React.useState(“蓝色”);
常量[bgColor,setBgColor]=React.useState(“黑色”);
//const[hasImage,setHasImage]=React.useState(true);
常量[fixedClasses,setFixedClasses]=React.useState(“下拉菜单”);
const[logo,setLogo]=React.useState(require(“assets/img/logo white.svg”);
//风格
const classes=useStyles();
常量主面板类=
类。主面板+
" " +
cx({
[classes.mainPanelSidebarMini]:miniActive,
[classes.mainPanelWithPerfectScrollbar]:
navigator.platform.indexOf(“Win”)>-1
});
//参考主面板分区
const mainPanel=React.createRef();
//影响而不是componentDidMount、componentDidUpdate和componentWillUnmount
React.useffect(()=>{
if(navigator.platform.indexOf(“Win”)>-1){
ps=新的完美滚动条(mainPanel.current{
对,,
抑制滚动:错误
});
document.body.style.overflow=“隐藏”;
}
addEventListener(“resize”,resizeFunction);
//指定此效果后如何清理:
返回函数cleanup(){
if(navigator.platform.indexOf(“Win”)>-1){
ps.destroy();
}
removeEventListener(“resize”,resizeFunction);
};
});
//用于更改组件状态的函数
常量handleImageClick=image=>{
设置图像(图像);
};
const handleColorClick=color=>{
设置颜色(颜色);
};
const handlegcolorclick=bgColor=>{
开关(bgColor){
“白色”案例:
setLogo(需要(“assets/img/logo.svg”);
打破
违约:
setLogo(需要(“assets/img/logo white.svg”);
打破
}
setBgColor(bgColor);
};
const handleFixedClick=()=>{
如果(fixedClasses==“下拉列表”){
setFixedClasses(“下拉显示”);
}否则{
setFixedClasses(“下拉列表”);
}
};
常量handleDrawerToggle=()=>{
setMobileOpen(!mobileOpen);
};
常量getRoute=()=>{
返回window.location.pathname!==“/admin/full screen maps”;
};
const getActiveRoute=路由=>{
让activeRoute=“默认品牌文本”;
for(设i=0;i{
返回路线图((道具,钥匙)=>{
如果(支柱倒塌){
返回路线(道具视图);
}
if(prop.layout==“/admin”){
返回(
);
}否则{
返回null;
}
});
};
常量边栏最小化=()=>{
setMiniActive(!miniActive);
};
常量resizeFunction=()=>{
如果(window.innerWidth>=960){
setMobileOpen(假);
}
};
返回(
{/*在/maps/full-screen-maps路径上,我们希望地图全屏显示-如果内容和conatiner类存在,这是不可能的,因为它们有一些填充,这会使地图变小*/}
{getRoute()(
{getRoutes(routes)}
) : (
{getRoutes(routes)}
)}
{getRoute()?:null}
);
}
My routes.js文件(要翻译“名称”项)

const dashRoutes=[
{
路径:“/dashboard”,

名称:“Dashboard”您可以这样做

import { withTranslation } from "react-i18next";
import i18n from "../../../../i18n"  // import here your i18n file

const dashRoutes = [
  {
    path: "/dashboard",
    name: i18n("Dashboard"), <--- need to translate this t("Dashboard") and subsequent name attributes below
    rtlName: "لوحة القيادة",
    icon: DashboardIcon,
    component: Dashboard,
    layout: "/admin"
  },
  {
    collapse: true,
    name: i18n("Page"),
    rtlName: "صفحات",
    icon: Image,
    state: "pageCollapse",

 ......

export default withTranslation()(dashRoutes);

我希望它能帮助您翻译数组名称。

谢谢,但这正是我一直在尝试的。您的选项1给出:TypeError:Object(…)不是一个函数您的选项2给出:钩子只能在函数组件体内部调用。您能给我看一下您的错误快照吗?@StevenDavisworth
import { withTranslation } from "react-i18next";
import i18n from "../../../../i18n"  // import here your i18n file

const dashRoutes = [
  {
    path: "/dashboard",
    name: i18n("Dashboard"), <--- need to translate this t("Dashboard") and subsequent name attributes below
    rtlName: "لوحة القيادة",
    icon: DashboardIcon,
    component: Dashboard,
    layout: "/admin"
  },
  {
    collapse: true,
    name: i18n("Page"),
    rtlName: "صفحات",
    icon: Image,
    state: "pageCollapse",

 ......

export default withTranslation()(dashRoutes);
import { useTranslation } from "react-i18next";
const {t} = useTranslation();

const dashRoutes = [
  {
    path: "/dashboard",
    name: t("Dashboard"), <--- need to translate this t("Dashboard") and subsequent name attributes below
    rtlName: "لوحة القيادة",
    icon: DashboardIcon,
    component: Dashboard,
    layout: "/admin"
  },
...