码迷,mamicode.com
首页 > 其他好文 > 详细

react context toggleButton demo

时间:2018-12-22 19:37:16      阅读:215      评论:0      收藏:0      [点我收藏+]

标签: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

 

//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

标签:alt   函数   bsp   包含   eee   UNC   tor   ===   function   

原文地址:https://www.cnblogs.com/begin256/p/10162096.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!