在react中使用context传值

父组件

import React, { Component } from 'react';
import {themeContext, theme} from './theme-context';
import ThemeButton from './theme-button';

export default class echarts3 extends Component {
    constructor(p){
        super(p);
        this.state = {
            theme: theme.light
        };
    }
// 中间组件
    Toolbar(p) {
        return (
            <ThemeButton onClick={p.chamgeTheme}>
                改变主题
            </ThemeButton>
        );
    }
    toggleTheme = ()=>{
        this.setState(state=>({
            theme: state.theme === theme.dark ?
            theme.light : theme.dark
        }));
        // console.log('点击');
    }
    render() {
        return (
        <div>
            <themeContext.Provider value={this.state.theme}>
                  <this.Toolbar chamgeTheme={this.toggleTheme}/>
            </themeContext.Provider>
        </div>
        );
    }
}

子组件

import React from 'react';
import {themeContext} from './theme-context';

function ThemeButton(props) {
    return (
        <themeContext.Consumer>
            {
                theme =>(
                    <button
                    {...props}
                    style={{backgroundColor: theme.background}}
                    />
                )
            }
        </themeContext.Consumer>
    );
}
export default ThemeButton;

存放数据的文件

import React from 'react';

export const theme = {
    light: {
        foreground: '#ffffff',
        background: '#222222'
    },
    dark: {
        foreground: '#000000',
        background: '#eeeeee'
    }

};
export const themeContext = React.createContext(theme.dark);


点击按钮可以切换背景颜色

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,303评论 4 61
  • 前言 您将在本文当中了解到,往网页中添加数据,从传统的dom操作过渡到数据层操作,实现同一个目标,两种不同的方式....
    itclanCoder阅读 26,021评论 1 12
  • vue概述 在官方文档中,有一句话对Vue的定位说的很明确:Vue.js 的核心是一个允许采用简洁的模板语法来声明...
    li4065阅读 7,297评论 0 25
  • 延迟一天~又到这个点,也只有到这个点才写得出此时的心情。 正在试着把固执的自己一点一点释放出来。慢慢把活着变...
    YSoul阅读 359评论 0 0
  • 你愈发晶莹 愈发水灵 没人知道你从哪朵云飘落 只有我清楚你的淅沥 你愈发伤心 愈发悲悯 没人知道你从何时变忧郁 只...
    Eliaukkkk阅读 201评论 3 3