Yvonne_D
2018-11-19 07:51
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> ); }}
<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>
把下划线下的改成href="javascript:;"应该就不会刷新页面了
基于实例的 React16 傻瓜课程
22387 学习 · 106 问题
相似问题