i18n

i18n

1.先新增三包語言包,都是js的object型態。

en.js

export default {
  lobby: 'lobby'
}

app.js

import tw from './i18n/zh-tw.js'
import cn from './i18n/zh-cn.js'
import en from './i18n/en.js'

if (!localStorage.getItem('lang')) {
  const userLang = window.navigator.language || window.navigator.userLanguage;
  localStorage.setItem('lang', userLang)
}

class App extends PureComponent {
  constructor() {
    super();
    this.state = {
      lang: '',
      langObject: ''
    }
  }
componentWillMount() {
    this.changeLang();
  }
  changeLang(){
    let lang = localStorage.getItem('lang');
    this.setState({ lang }, () => {
      if (lang === "zh-TW") {
        this.setState({langObject: tw})
      }
      if (lang === "en") {
        this.setState({langObject: en})
      }
      if (lang === "zh-CN") {
        this.setState({langObject: cn})
      }
    });
  }

  render() {
    window.context = this;
    return (
      <Router>
        <div>
          <Route path="/lobby" component={Lobby} />
        </div>
      </Router>
    );
  }
}

lobby.js

import React, { PureComponent } from 'react';
import { withRouter } from 'react-router-dom';
import './index.css'
import Header from '../../Component/Header'
class lobby extends PureComponent {
  constructor() {
    super();
    this.state = {

    }
  }
  render() {
    const l = window.context.state.langObject
    return (
          <div>
            <Header/>
            {l['lobby']}
          </div>
    );
  }
}

export default withRouter(lobby);

Header.js

import React, { PureComponent } from 'react';

class Header extends PureComponent {
  changeLang(e) {
    localStorage.setItem('lang', e.target.value)
    window.context.setState({'lang': e.target.value});
    window.context.changeLang();
  }
  render() {
    return (
      <div>
        <select defaultValue={localStorage.getItem('lang')} onChange={(e) => this.changeLang(e)}>
          <option value="en">English</option>
          <option value="zh-TW">中文-繁體</option>
          <option value="zh-CN">中文-簡體</option>
        </select>
      </div>
    );
  }
}


export default Header;

Last updated