//toggleButton demo:
//code:
//1.Appb.js:
import React from ‘react‘; import {ThemeContext, themes} from ‘./theme-context‘; import ThemeTogglerButton from ‘./theme-toggler-button‘; class Appb extends React.Component { constructor(props) { super(props); this.toggleTheme = () => { this.setState(state => ({ theme: state.theme === themes.dark ? themes.light : themes.dark, })); }; // State 包含了 updater 函数 所以它可以传递给底层的 context Provider this.state = { theme: themes.light, toggleTheme: this.toggleTheme, }; } render() { // 入口 state 传递给 provider return ( <ThemeContext.Provider value={this.state}> <Content /> </ThemeContext.Provider> ); } } function Content() { return ( <div> <ThemeTogglerButton /> </div> ); } export default Appb
//2.theme-toggler-button.js:
import {ThemeContext} from ‘./theme-context‘; import React from ‘react‘; function ThemeTogglerButton() { // Theme Toggler 按钮不仅接收 theme 属性 // 也接收了一个来自 context 的 toggleTheme 函数 return ( <ThemeContext.Consumer> {({theme, toggleTheme}) => ( <button onClick={toggleTheme} style={{backgroundColor: theme.background}}> Toggle Theme </button> )} </ThemeContext.Consumer> ); } export default ThemeTogglerButton;
//3.theme-context.js:
// 确保默认值按类型传递 // createContext() 匹配的属性是 Consumers 所期望的 import React from ‘react‘; export const themes = { light: { foreground: ‘#ffffff‘, background: ‘#222222‘, }, dark: { foreground: ‘#000000‘, background: ‘#eeeeee‘, }, }; export const ThemeContext = React.createContext({ theme: themes.dark, toggleTheme: () => {}, });
原文地址:https://www.cnblogs.com/begin256/p/10162096.html
时间: 2024-10-14 19:51:22