父组件
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);
点击按钮可以切换背景颜色