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

使用i18next调用props.t报不是函数错误,withTranslation包裹后仍失效如何解决

问题根因

  • react-router 的 <Route> 组件 render 回调接收的 props 参数仅包含路由原生属性:match、location、history,不会继承外层组件的自定义属性
  • withTranslation() 注入的 t 函数是挂载到当前 Router 组件自身的 props 上的,和 render 回调内的路由 props 是完全独立的两个对象,因此从路由 props 里读取 t 自然会报错不是函数。

修复方案

方案1:直接使用外层组件注入的t函数

将 render 回调的参数重命名避免命名冲突,直接引用外层 Router 组件的 props 里的 t 即可:

// 示例为函数组件写法,类组件替换为 this.props.t 即可
const Router = (props) => {
  // 此处的 props 是被 withTranslation 注入了 t 函数的组件props
  return (
    <Route
      exact
      path="/services/edit"
      render={(routeProps) => {
        return (
          <MainLayout title={props.t("SERVICES")}  >
            <ServicesEdit {...routeProps} />
          </MainLayout>
        );
      }}
    />
  )
}

export default withTranslation()(Router)

方案2:给子组件单独注入翻译能力

如果 t 函数是给 ServicesEdit 组件使用,直接给该组件套上 withTranslation() 即可,不需要从外层逐层传递,更符合 react-i18next 的使用规范。

方案3:react-router v6 版本适配

如果使用的是 v6 版本的 react-router,直接改用 element 属性定义路由组件,无需处理render回调的props隔离问题:

<Route exact path="/services/edit" element={
  <MainLayout title={props.t("SERVICES")}>
    <ServicesEdit />
  </MainLayout>
} />

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 19:12:00