React类组件中如何正确使用react-i18next的useTranslation Hook
错误原因
useTranslation 是React专属Hook,仅允许在函数组件、自定义Hook的内部调用,你在类组件外部直接调用Hook不符合React的使用规则,因此无法正常获取t和i18n实例。
解决方法
使用react-i18next官方为类组件提供的withTranslation高阶组件适配,操作步骤如下:
- 替换导入的
useTranslation为withTranslation - 删除组件外部调用
useTranslation的代码 - 用
withTranslation()包裹你的类组件,翻译相关的能力会自动注入到组件的props中 - 类内部使用时直接从
this.props取t和i18n即可
修改后的完整代码
import React, { Component } from 'react'; import { inject, observer } from "mobx-react"; // 替换导入为withTranslation import { withTranslation } from 'react-i18next'; import Timer from '../../components/common/Timer'; import FrenchLanguage from '../../images/france-48.png'; import EnglishLanguage from '../../images/england-48.png'; import './brothers.scss'; // 类名首字母大写,符合React组件命名规范 class Brothers extends Component { constructor(props) { super(props); this.stores = this.props.Stores; } updateResponsive = () => { this.forceUpdate() } changeLanguage = (Language) => { // 从props中获取i18n实例 this.props.i18n.changeLanguage(Language) } showAlert = () =>{ // 后续需要翻译的文案直接调用this.props.t传入对应key即可 alert("I'm an alert : " + this.props.t('your.translation.key')); } render() { return ( <div className={"full-screen main-grid"}> <Timer task={this.updateResponsive} interval={1000} /> <div className="title-containers"> <div className="language"> <img onClick={() => this.changeLanguage('fr')} src={FrenchLanguage} alt="French"/> <img onClick={() => this.changeLanguage('en')} src={EnglishLanguage} alt="English"/> </div> </div> </div> ); } } // 导出时用withTranslation包裹组件,注意调用顺序 export default inject("Stores")(observer(withTranslation()(Brothers)));
如果你的多语言配置了独立命名空间,只需要在withTranslation的参数里传入对应的命名空间即可,比如withTranslation('common')。
内容的提问来源于stack exchange,提问作者Ibrahim
相关产品推荐
相关产品推荐

