react-i18next v10.9.0能否不使用hooks?替代translate方案咨询
如何在react-i18next v10.9.0中不使用hooks替代
translate 当然可以在react-i18next v10.9.0版本中避开hooks,用官方提供的高阶组件(HOC)来替代旧版的translate!
v10版本确实移除了translate HOC,转而推荐使用withTranslation作为非hooks场景下的替代方案——它完美适配类组件,也能用于函数组件,完全不需要依赖hooks。
具体用法步骤:
导入
withTranslation
从react-i18next中导入这个高阶组件,替代原来的translate:import { withTranslation } from 'react-i18next';用
withTranslation包裹你的组件对于类组件(最常见的非hooks场景):
import React from 'react'; import { withTranslation } from 'react-i18next'; class WelcomeComponent extends React.Component { render() { // 通过props获取翻译函数`t`(short for translate) const { t } = this.props; return <h1>{t('greeting')}</h1>; } } // 默认使用全局命名空间,若需指定命名空间可传入参数,比如withTranslation('auth') export default withTranslation()(WelcomeComponent);对于不想用hooks的函数组件:
import { withTranslation } from 'react-i18next'; function ProfileComponent({ t }) { return <p>{t('profile.description')}</p>; } export default withTranslation()(ProfileComponent);
额外配置(可选)
如果需要自定义翻译函数的名称(比如想沿用旧版的translate而不是t),可以通过高阶组件的配置参数实现:export default withTranslation({ translateFuncName: 'translate' })(WelcomeComponent);这样组件内就可以通过
this.props.translate来调用翻译函数了。
注意点
withTranslation会自动将i18n实例也注入到组件props中,如果你需要直接调用i18n的方法(比如切换语言),可以直接从props中获取:const { i18n } = this.props;- 这个方案完全符合v10版本的官方规范,不存在兼容性问题,放心使用即可。
内容的提问来源于stack exchange,提问作者Nands
相关产品推荐
相关产品推荐

