类组件中使用react i18next的withTranslation传入动态namespace参数
解决方案
你现有写法的问题在于withTranslation高阶组件的执行时机在模块导出阶段,早于类组件的实例化过程,此时params还是初始空值,constructor内的赋值操作无法作用到导出阶段的withTranslation入参上,因此无法拿到动态namespace。
方案1:函数组件桥接(实现成本最低)
你不需要修改原有类组件的业务逻辑,仅在外层套一层轻量的函数组件,即可使用useTranslation的动态传参能力:
import { useTranslation } from "react-i18next" import { PureComponent } from "react" class SecondScreen extends PureComponent { // 原有类组件逻辑保持不变,翻译方法t从props中获取即可 render() { const { t } = this.props // 原有渲染逻辑 } } // 外层桥接函数组件 const SecondScreenWrapper = (props) => { const { navigation } = props const params = navigation.getParam("params", {}) // 动态传入namespace const { t } = useTranslation([`namespace1/${params}`]) // 透传所有属性和翻译方法给类组件 return <SecondScreen {...props} t={t} /> } export default SecondScreenWrapper
方案2:纯类组件实现(无需使用Hooks)
如果完全不希望引入Hooks,可以在类组件生命周期内手动加载动态namespace:
import { withTranslation } from "react-i18next" import { PureComponent } from "react" class SecondScreen extends PureComponent { constructor(props) { super(props) const { navigation } = props this.params = navigation.getParam("params", {}) this.state = { namespaceLoaded: false } } componentDidMount() { const dynamicNS = `namespace1/${this.params}` // 手动加载动态namespace this.props.i18n.loadNamespaces(dynamicNS, () => { // 加载完成后更新状态触发重渲染,可按需替换默认namespace this.setState({ namespaceLoaded: true }) }) } render() { // 加载过程中可自定义占位UI,避免文案缺失 if (!this.state.namespaceLoaded) return null // 调用翻译时指定动态namespace即可 const translate = (key) => this.props.t(key, {}, { ns: `namespace1/${this.params}` }) // 原有渲染逻辑 } } // 先传入任意公共默认namespace即可 export default withTranslation('common')(SecondScreen)
内容的提问来源于stack exchange,提问作者Sajith Wijerathne
相关产品推荐
相关产品推荐

