我正在使用react.i18next框架(https://react.i18next.com/)。我对React很陌生,但是国际化正在使用withTranslation HOC(https://react.i18next.com/latest/withtranslation-hoc)。
问题出在Modal内部的一个特定子组件中。
这些是我的index.jsx文件中涉及的行:
...
import { I18nextProvider } from 'react-i18next';
import i18n from './i18n';
const Loader = () => (
<div>loading texts...</div>
);
const Index = () => (
<Suspense fallback={<Loader/>}>
<I18nextProvider i18n={i18n}>
<Provider store={store}>
<ConnectedRouter history={history}>
<App/>
</ConnectedRouter>
</Provider>
</I18nextProvider>
</Suspense>
)
这些都在我的login.jsx中(登录模式)。 此处的翻译正常:
...
import { withTranslation } from 'react-i18next';
class LoginModal extends Component {
render() {
const { t, i18n } = this.props;
const changeLanguage = (lng) => {
i18n.changeLanguage(lng);
};
return (
<Modal isOpen={this.props.show} toggle={this.props.toggle} className={this.props.className}>
<ModalHeader toggle={this.props.toggle}>Login</ModalHeader>
<ModalBody>
<p>{t('title')}</p>
{this.state.isLogin ? (<LoginForm />) : (<RegisterForm />)}
</ModalBody>
</Modal>
);
}
}
export default withTranslation("landing")(LoginModal);
但是当我尝试以相同的方式翻译子组件(LoginForm)中的内容时:
...
import { withTranslation } from 'react-i18next';
constructor(props) {
super(props)
}
render() {
const { t, i18n } = this.props;
const changeLanguage = (lng) => {
i18n.changeLanguage(lng);
};
return (
<p>FORM</p>
)
}
}
export default withTranslation("form")(LoginForm)
我收到以下错误:
useTranslation.js:12 Uncaught TypeError: Cannot read property 'i18n' of undefined at useTranslation (useTranslation.js:12)
起初,我认为问题与上下文有关,因为模态位于包含包装器的App组件之外,但是我尝试在模态内部进行操作,如您在前面的示例中看到的那样,此处的翻译工作正常。
我试图将i18n道具从模式传递给LoginForm子组件,但我认为国际化框架不是从本地i18n而是从上下文读取i18n属性。这些是与框架代码内的错误相关的行:
var _ref = getHasUsedI18nextProvider() ? useContext(I18nContext) : {},
i18nFromContext = _ref.i18n;
我做了很多研究,但得到了一些类似的错误,但是没有什么可以解决我的问题。使用HOC进行翻译的信息不是很多,这是使用i18next对我有用的唯一方法。
任何帮助将不胜感激。
预先感谢, 教育