在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('點(diǎn)擊');
    }
    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;

存放數(shù)據(jù)的文件

import React from 'react';

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

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


點(diǎn)擊按鈕可以切換背景顏色

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫、插件、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 15,659評論 4 61
  • 前言 您將在本文當(dāng)中了解到,往網(wǎng)頁中添加數(shù)據(jù),從傳統(tǒng)的dom操作過渡到數(shù)據(jù)層操作,實(shí)現(xiàn)同一個目標(biāo),兩種不同的方式....
    itclanCoder閱讀 26,255評論 1 12
  • vue概述 在官方文檔中,有一句話對Vue的定位說的很明確:Vue.js 的核心是一個允許采用簡潔的模板語法來聲明...
    li4065閱讀 7,624評論 0 25
  • 延遲一天~又到這個點(diǎn),也只有到這個點(diǎn)才寫得出此時的心情。 正在試著把固執(zhí)的自己一點(diǎn)一點(diǎn)釋放出來。慢慢把活著變...
    YSoul閱讀 396評論 0 0
  • 你愈發(fā)晶瑩 愈發(fā)水靈 沒人知道你從哪朵云飄落 只有我清楚你的淅瀝 你愈發(fā)傷心 愈發(fā)悲憫 沒人知道你從何時變憂郁 只...
    Eliaukkkk閱讀 215評論 3 3

友情鏈接更多精彩內(nèi)容