问答详情
源自:5-2 Context 编码

点击更换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>    );  }}


提问者:Yvonne_D 2018-11-19 07:51

个回答

  • 奋斗的乐儿
    2018-11-27 14:54:37
    已采纳

    <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:;"应该就不会刷新页面了

  • qq_慕斯卡2406361
    2019-10-12 18:10:25

    完整代码已经上传至GitHub:https://github.com/shanlanCoding/react_test