localeContext.js 1.33 KB
Newer Older
1
import React from 'react';
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
2
import { addLocaleData, IntlProvider } from 'umi/locale';
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
import { LocaleProvider } from 'antd';
import enLocale from './en-US';
import cnLocale from './zh-CN';

const Context = React.createContext();

function getLang() {
  if (window.localStorage && localStorage.getItem('locale')) {
    return localStorage.getItem('locale');
  }
  return (navigator.language || navigator.browserLanguage).toLowerCase() === 'en-us'
    ? 'en-US'
    : 'zh-CN';
}

export class LocalComponent extends React.PureComponent {
  state = {
    locale: getLang(),
  };

  changeLocal = () => {
    this.setState({
      locale: getLang(),
    });
  };

  render() {
    const { children } = this.props;
    const { locale } = this.state;
    return (
      <Context.Provider
        value={{
          appLocale: locale === 'zh-CN' ? cnLocale : enLocale,
          changeLocal: this.changeLocal,
        }}
      >
        <Context.Consumer>
          {({ appLocale }) => {
            addLocaleData(appLocale.data);
            return (
              <IntlProvider locale={appLocale.locale} messages={appLocale.messages}>
                <LocaleProvider locale={appLocale.antd}>{children}</LocaleProvider>
              </IntlProvider>
            );
          }}
        </Context.Consumer>
      </Context.Provider>
    );
  }
}
export default Context;