版权声明:欢迎关注博主公众号:矿洞程序员 https://blog.csdn.net/qq_32423845/article/details/89334853
实现主题切换
一、定义2中不同主题
代码语言:javascript复制const themes = {
light: {
classnames: 'btn btn-primary',
bgColor: 'red',
color: '#000'
},
dark: {
classnames: 'btn btn-light',
bgColor: '#blue',
color: '#fff'
},
}
二、定义Context;
代码语言:javascript复制import React from 'react'
const ThemeContext =React.createContext()
export default ThemeContext
三、使用context.Provider
代码语言:javascript复制
render() {
return (
<ThemeContext.Provider value={themes.light}>
<div className="App">
<header className={"App-header"}>
<img src={logo} className={"App-logo"} alt={"logo"}/>
<h2>欢迎来到矿洞程序员</h2>
<a href="#theme-switcher" className="btn btn-light" onClick={()=>{this.changeTheme('light')}}>浅色主题</a>
<a href="#theme-switcher" className="btn btn-secondary" onClick={()=>{this.changeTheme('dark')}}>深色主题</a>
</header>
<ThemeBar/>
</div>
</ThemeContext.Provider>
);
}
四:定义样式消费组件
代码语言:javascript复制import React from 'react'
import ThemeContext from './Theme-context'
const ThemeBar = () =>{
return (
<ThemeContext.Consumer>
{
theme=>{
// console.log(theme)
return (
<div className="alert mt-5" style={{backgroundColor:theme.bgColor,color:theme.color}}>样式区域
<button>样式按钮</button>
</div>
)
}
}
</ThemeContext.Consumer>
)
}
export default ThemeBar
五、查看效果: