//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. SaltStack 基础

    介 SaltStack是基于Python开发的一套C/S架构配置管理工具.它的底层使用ZeroMQ消息队列pub/sub方式通信,使用SSL证书签发的方式进行认证管理.号称世界上最快的消息队列Zero ...

  2. string、char *的转换

    string转char* 主要有三种方法可以将str转换为char*类型,分别是:data(); c_str(); copy(); data()方法 string str = "hello& ...

  3. pytest+jenkins安装+allure导出报告

    环境安装: windows7+64位 pytest:4.0.2 allure的安装:allure的python库pytest-allure-adaptor jenkins的安装:2.138.2 JDK ...

  4. #Go# 点滴积累

    此篇仅为不断记录趟过的坑 StringToTimestamp import ( "time" ) const TimeFormat = "2006-01-02T15:04 ...

  5. LCS and LIS

    LCS #include<bits/stdc++.h> using namespace std; typedef long long ll; int n,m; char s[1005],t ...

  6. js解决千分符问题

    js脚本function: //js数字千分符处理 function commafy(num) { num = num + ""; var re = /(-?\d+)(\d{3}) ...

  7. android4.0 4.1 4.2 4.3 4.4新特性

    http://blog.csdn.net/kaiyang45/article/details/7179349 4.0 http://digi.tech.qq.com/a/20120628/000827 ...

  8. MongoDB数据库及其Python用法

    一 .命令行模式 mongo # 进入mongodb命令行模式 show dbs use taobao # 进入该数据库,如不存在则创建之 show tables # 条件操作符 (>) 大于 ...

  9. PHP之string之ltrim()函数使用

    ltrim (PHP 4, PHP 5, PHP 7) ltrim - Strip whitespace (or other characters) from the beginning of a s ...

  10. Maven项目中Spring整合Mybatis

    Maven项目中Spring整合Mybatis 添加jar包依赖 spring需要的jar包依赖 <dependency> <groupId>org.springframewo ...