点击更换dark主题之后,只会闪一下,又变回light主题
theme-context.js
import React from 'react'const ThemeContext = React.createContext()export default ThemeContext
themebar.js
import React from 'react'import ThemeContext from '../theme-context'const ThemeBar = () => { return ( <ThemeContext.Consumer> { theme=>{ return( <div className="alert mt-5" style={{backgroundColor:theme.bgColor,color:theme.color}}> StyleSheet Section <button className={theme.classnames}>submit</button> </div> ) } } </ThemeContext.Consumer> )}export default ThemeBar
app.js
const themes = { light: { classnames: 'btn btn-primary', bgColor: '#eeeeee', color: '#000' }, dark: { classnames: "btn btn-light", bgColor: "#222222", color: "#fff" }}class App extends Component { constructor(props) { super(props) this.state = { theme: 'light' } this.changeTheme = this.changeTheme.bind(this)
changeTheme(theme) { this.setState({ theme, }) } render() { return ( <ThemeContext.Provider value={themes[this.state.theme]}> <div className="App"> <header> <a href="theme-switcher" className="btn btn-light" onClick={()=>{this.changeTheme('light')}}>Light</a> <a href="theme-switcher" className="btn btn-secondary" onClick={()=>{this.changeTheme('dark')}}>Dark</a> </header> <ThemeBar /> </div> </ThemeContext.Provider> ); }}