react context toggleButton demo
Posted begin256
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了react context toggleButton demo相关的知识,希望对你有一定的参考价值。
//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: () => {}, });
以上是关于react context toggleButton demo的主要内容,如果未能解决你的问题,请参考以下文章
React Context 和 Storybook:在组件故事中更改 React Context 的值
(React Context 初学者)使用 react-router-dom 更改页面时,React Context 不启动