Как получить данные из контекста
Я пытаюсь создать переключатель свелой на темную тему. У меня есть три файла: Theme-context, где я создаю контекст, Header - где будет кнопка для переключения темы, Content - где тема изменится Я не могу понять, как передать значение темы из файла Header в Content, чтобы тема изменилась. Как это может быть сделано? Спасибо)
Header
import React, {useState} from "react";
import {Theme_Context, themes} from "../Contexts/Theme_Context";
export function Header () {
let [theme, setTheme] = useState(themes.light);
let toggleTheme = () => {
setTheme((prevTheme) => prevTheme === themes.light ? themes.dark : themes.light)
}
return (<header className="header">
<button onClick={toggleTheme}>Change Theme</button>
</header>)
}
Theme_Context
import React, {createContext} from "react";
export let themes = {
light: {
background: '#eeeeee',
textColor: '#444444'
},
dark: {
background: '#444444',
textColor: '#eeeeee'
},
};
export let Theme_Context = createContext(themes.light);
Content
import React, {useState, useEffect} from "react";
import {Theme_Context} from "../Contexts/Theme_Context";
export default Content = () => {
return (<div>
<Theme_Context.Provider value={theme}/>
// Content
</Theme_Context.Provider>
</div>)
}
Ответы (1 шт):
Автор решения: Konstantin Modin
→ Ссылка
В контексте передаём текущую тему и функцию для её изменения. Далее в любом компоненте который находится внутри ThemeContext.Provider можно получить доступ к ним с помощью React.useContext. Получается примерно так:
import React from "react";
// файл 1
// импортируется там где нужен
export const themes = {
light: {
background: "#eeeeee",
textColor: "#444444",
},
dark: {
background: "#444444",
textColor: "#eeeeee",
},
};
// файл 2
// import React from "react";
export const ThemeContext = React.createContext();
const defaultTheme = "light";
const App = () => {
const [theme, setTheme] = React.useState(defaultTheme);
const toggleTheme = () => setTheme(theme === "light" ? "dark" : "light");
return (
<div>
<ThemeContext.Provider value={[theme, toggleTheme]}>
<Header />
</ThemeContext.Provider>
</div>
);
};
export default App;
// файл 3
// import React from "react";
// import { themes } from ...
// import { ThemeContext } from ...
const Header = () => {
const [theme, toggleTheme] = React.useContext(ThemeContext);
const colors = themes[theme];
return (
<header
className="header"
style={{ backgroundColor: colors.background, color: colors.textColor }}
>
<h3>Current theme is : {theme}</h3>
<h3>Background is : {colors.background}</h3>
<h3>TextColor is : {colors.textColor}</h3>
<button onClick={toggleTheme}>Change Theme</button>
</header>
);
};
// export default Header;