如何使用React上下文API实现多语言站点

时间:2018-10-23 06:05:07

标签: javascript json reactjs

我有以下代码,到目前为止一切正常,但是内容是静态的。我正在寻找如何实现lang切换器,但是Im堆栈上是关于如何使用每个选定的lang导入不同的obj。

import React, { Component, createContext } from "react";
import { en } from "./components/language/en";
import { gr } from "./components/language/gr";

const Context = createContext();

export class Provider extends Component {
  constructor() {
   super();
   this.state = {
     lang: en
   };
 }

selectLanguage = e => {
   this.setState({ lang: e.target.value });
};

render() {
  return (
    <Context.Provider
      value={{ lang: this.state.lang, selectLang: this.selectLanguage 
  }}
  >
     {this.props.children}
    </Context.Provider>
  );
 }
}

export const Consumer = Context.Consumer;

1 个答案:

答案 0 :(得分:1)

首先,您需要创建对象来保存所有json:

import { en } from "./components/language/en";
import { gr } from "./components/language/gr";

var langs = {
    en: en,
    gr: gr 
};

然后将selectLanguage更改为:

selectLanguage = e => {
   const langKey = e.target.value;
   this.setState({ lang: langs[langKey] });
};