使用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
相关产品推荐
相关产品推荐

