0
我開發了一個使用reactjs和redux的應用程序。我使用的語言是西班牙語。我想這個應用程序是多語言。語言有兩種選擇。一個是默認的西班牙語,另一個是英語。有一個下拉菜單供用戶選擇語言。當用戶選擇英文時,所有的字符串應該被轉換成英文。我查看了react-intl包,但我很難理解消息道具應該如何獲得IntlProvider。無法理解用於語言翻譯的react-intl的工作過程
現在,我已經爲我的英語JSON文件如下:
en.js
export default [
{
"id": "Nav__registration_text",
"defaultMessage": "Registration",
},
{
"id": "Nav__login_text",
"defaultMessage": "Login",
},
]
import { connect } from 'react-redux';
import { IntlProvider } from 'react-intl';
function mapStateToProps(state) {
console.log('locale is', state.locale.locale);
return { locale: state.locale.locale };
}
export default connect(mapStateToProps)(IntlProvider);
import { Provider } from 'react-redux';
import { addLocaleData } from 'react-intl';
import en from 'react-intl/locale-data/en';
import es from 'react-intl/locale-data/es';
import App from './components/app';
import reducers from './reducers';
const createStoreWithMiddleware = applyMiddleware()(createStore);
addLocaleData(en);
addLocaleData(es);
ReactDOM.render(
<Provider store={createStoreWithMiddleware(reducers)}>
<ConnectedIntlProvider>
<App />
</ConnectedIntlProvider>
</Provider>
, document.querySelector('.app'));
action.js
export function selectedLocale(locale) {
console.log('locale', locale);
return {
type: 'LOCALE_SELECTED',
locale
};
}
reducer
const initialState = {
locale: 'es',
};
export const localeReducer = (state = initialState, action) => {
switch (action.type) {
case 'LOCALE_SELECTED':
return { ...initialState, locale: action.locale };
default:
return state;
}
};
Nav.js
import { intlShape, injectIntl, defineMessages } from 'react-intl';
const Nav = (props) => (
<Router>
<div>
<nav className="navbar navbar-default">
<div className="container-fluid">
<div className="collapse navbar-collapse">
<ul className="nav navbar-nav navbar-right nav-social-icon">
<li className="dropdown">
<a
href=""
className="dropdown-toggle"
data-toggle="dropdown"
role="button"
aria-haspopup="true"
aria-expanded="false"
>
ES
<span className="caret" />
</a>
<ul className="dropdown-menu">
<li onClick={() => props.selectedLocale('en-Us')}>
en-US
</li>
<li onClick={() => props.selectedLocale('es')}>
es
</li>
</ul>
</li>
<li className="btn-group">
<button
className="btn btn-default"
onClick={props.showModal}
>
<Link to={{ pathname: '/signup' }}>Regístrate</Link> // wanted to change this to english when user selects english language from dropdown
</button>
<button
onClick={props.showModal}
className="btn btn-default"
>
<Link to={{ pathname: '/login' }}>Iniciar sesión</Link>
</button>
</li>
</ul>
</div>
</div>
</nav>
</div>
</Router>
);
Nav.propTypes = {
intl: intlShape.isRequired,
};
export default injectIntl(Nav);
我不明白它的文檔。請在此引導我。