我有以下代码,到目前为止一切正常,但是内容是静态的。我正在寻找如何实现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;
答案 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] });
};