//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的更多相关文章

  1. React context基本用法

    React的context就是一个全局变量,可以从根组件跨级别在React的组件中传递.React context的API有两个版本,React16.x之前的是老版本的context,之后的是新版本的 ...

  2. [React] Prevent Unnecessary Rerenders of Compound Components using React Context

    Due to the way that React Context Providers work, our current implementation re-renders all our comp ...

  3. React Context API

    使用React 开发程序的时候,组件中的数据共享是通过数据提升,变成父组件中的属性,然后再把属性向下传递给子组件来实现的.但当程序越来越复杂,需要共享的数据也越来越多,最后可能就把共享数据直接提升到最 ...

  4. 探索 Redux4.0 版本迭代 论基础谈展望(对比 React context)

    Redux 在几天前(2018.04.18)发布了新版本,6 commits 被合入 master.从诞生起,到如今 4.0 版本,Redux 保持了使用层面的平滑过渡.同时前不久, React 也从 ...

  5. React Hooks +React Context vs Redux

    React Hooks +React Context vs Redux https://blog.logrocket.com/use-hooks-and-context-not-react-and-r ...

  6. [译]迁移到新的 React Context Api

    随着 React 16.3.0 的发布,context api 也有了很大的更新.我已经从旧版的 api 更新到了新版.这里就分享一下我(作者)的心得体会. 回顾 下面是一个展示如何使用旧版 api ...

  7. 使用react context实现一个支持组件组合和嵌套的React Tab组件

    纵观react的tab组件中,即使是github上star数多的tab组件,实现原理都非常冗余. 例如Github上star数超四百星的react-tab,其在render的时候都会动态计算哪个tab ...

  8. [译]React Context

    欢迎各位指导与讨论 : ) 前言 由于笔者英语和技术水平有限,有不足的地方恳请各位指出.我会及时修正的 O(∩_∩)O 当前React版本 15.0.1 时间 2016/4/25 正文 React一个 ...

  9. React Native官方DEMO

    官方给我们提供了UIExplorer项目,这里边包含React Native的基本所有组件的使用介绍和方法. 运行官方DEMO步骤如下 安装react native环境 React Native项目源 ...

随机推荐

  1. day 13 课后作业

    # -*- coding: utf-8 -*-# @Time : 2019/1/7 18:00# @Author : Endless-cloud# @Site : # @File : day 13 课 ...

  2. spring中scope的prototype与singleton区别

    最近在研究单例模式,突然想起项目中以下配置,scope="singleton" 和 scope="prototype"到底有何区别呢?以下做下简要分析. < ...

  3. 2016级算法期末上机-F.中等·AlvinZH's Fight with DDLs II

    1118 AlvinZH's Fight with DDLs II 思路 中等题,贪心. 理解题意,每次攻击中,可以使某个敌人生命值-1,自己生命值减去∑存活敌人总攻击力. 贪心思想,血量少攻击高的要 ...

  4. Python3 操作系统与路径 模块(os / os.path / pathlib)

    #!/usr/bin/env python # coding=utf-8 __author__ = 'Luzhuo' __date__ = '2017/5/7' import os def os_de ...

  5. WCF系列教程之WCF服务宿主与WCF服务部署

    本文参考自http://www.cnblogs.com/wangweimutou/p/4377062.html,纯属读书笔记,加深记忆. 一.简介 任何一个程序的运行都需要依赖一个确定的进程中,WCF ...

  6. git 检出项目部分目录(稀疏检出)

    git clone 会把整个项目都clone下来,对于大项目git status比较慢,每次pull时候也拉取一些无关的代码或者文件:git可以实现像svn一样检出部分目录 步骤: git clone ...

  7. bash切割文件

    split -l 100 ./x01.txt -d -a 3 --additional-suffix=.txt 将 x01.txt文件,-l 100 按照每个100行,  -d 以数字累加, -a 3 ...

  8. 介绍nodejs中的path模块的几个方法

    webpack中常用的: var path = require('path') 是nodejs中的path模块,介绍一下webpack中常用的几个path模块的方法: 应用node环境的时候,这个pa ...

  9. redis数据类型(四)list类型

    一.list类型 list是一个链表结构,可以理解为一个每个子元素都是 string 类型的双向链表. 主要功能是push.pop.获取一个范围的所有值等. 操作中key理解为链表的名字. 二.Lis ...

  10. 第十章、vim 程序编辑器

    第十章.vim 程序编辑器   1. vi 与 vim 1.1 为何要学 vim 2. vi 的使用 2.1 简易执行范例 2.2 按键说明 2.3 一个案例的练习 2.4 vim 的暂存档.救援回复 ...