概述
需要国际化的实际应用程序,使用i18next实现。
问题
在项目结构中,有constants.js(普通JS),我正在尝试获取i18next.t()
进行翻译。请找到相关代码。
index.js
import React,{Suspense} from "react";
import ReactDOM from "react-dom";
import "./style/index.scss";
import App from "./app";
import createSagaMiddleware from "redux-saga";
import { createStore, applyMiddleware } from "redux";
import { Provider } from "react-redux";
import rootReducer from "./reducers";
import rootSaga from "./sagas";
import './i18n';
const sagaMiddleware = createSagaMiddleware();
const store = createStore(rootReducer, applyMiddleware(sagaMiddleware));
sagaMiddleware.run(rootSaga);
ReactDOM.render(<Provider store={store}>
<App store={store} />
</Provider>,
document.getElementById("root")
);
App.js
import React from "react";
import "./App.scss";
import MyOrders from "../component/my-orders";
import { toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import i18n from 'i18next'
toast.configure({ autoClose: 5000 });
const changeLanguage = (lng) => {
i18n.changeLanguage(lng);
};
const App = () => {
return (
<div className="App">
<div align="left">
<button className="btn btn-group-sm" onClick={() => changeLanguage('de')}>German</button>
<button className="btn btn-group-sm" onClick={() => changeLanguage('en')}>English</button>
</div>
<MyOrders />
</div>
);
};
export default App;
i18n.js
import i18n from "i18next";
import detector from "i18next-browser-languagedetector";
import { reactI18nextModule } from "react-i18next";
import translationEN from '../public/locales/en/translation.json';
import translationDE from '../public/locales/de/translation.json';
// the translations
const resources = {
en: {
translation: translationEN
},
de: {
translation: translationDE
}
};
i18n
.use(detector)
.use(reactI18nextModule) // passes i18n down to react-i18next
.init({
resources,
lng: "en",
fallbackLng: "en", // use en if detected lng is not available
interpolation: {
escapeValue: false // react already safes from xss
}
});
export default i18n;
constants.js(纯JavaScript文件,导出多个常量对象)
//here I want to translate content
我没有运气就尝试了以下解决方案:Solution
您可以从i18n
文件导入i18n.js
实例,该实例上包含t
。
import i18n from '../i18n';
i18n.t // <- use it.