react context

写一个切换页面主题的demo

 

 

App.js

import ThemeContext from './theme-context'
import ThemeBar from './component/ThemeBar'
const theme = {
  light: {
    className: 'btn btn-primary',
    bgColor: '#eeeeee',
    color: '#000'
  },
  dark: {
    className: '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={theme.[this.state.theme]}>
        <div className="App">
          <header className="App-header">
            <a className="btn btn-light"
              onClick={() => { this.changeTheme('light')} }>浅色主题</a>
            <a className="btn btn-secondary"
              onClick={() => { this.changeTheme('dark')} }>深色主题</a>
          </header>
          <ThemeBar></ThemeBar>
        </div>
      </ThemeContext.Provider>
      
    )
  } 
}

export default App;
theme-context.js

import React from 'react';
const ThemeContext = React.createContext();
export default ThemeContext;
component/ContextBar.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} }>
                            样式区域
                            <button className={theme.className}>按钮</button>
                        </div>
                    )
                }
            }

        </ThemeContext.Consumer>
    )
}

export default ThemeBar;

 

posted @ 2020-11-03 19:39  氧化成风  阅读(69)  评论(0编辑  收藏  举报