标签:alt 函数 bsp 包含 eee UNC tor === function
//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
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;
// 确保默认值按类型传递 // 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: () => {}, });
react context toggleButton demo
标签:alt 函数 bsp 包含 eee UNC tor === function
原文地址:https://www.cnblogs.com/begin256/p/10162096.html