• 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;
  • 相关阅读:
    解析#pragma指令
    查看内核版本和发行版本

    unix 环境高级编成 apue.h ,apueerror.h的代码
    类string的构造函数、拷贝构造函数和析构函数 (转)
    归并排序
    C++ 中调用其他应用程序的方法
    [MySQL] MySQL的Grant命令
    static的作用
    白话经典算法系列之七 堆与堆排序 (转)
  • 原文地址:https://www.cnblogs.com/150536FBB/p/13922061.html
Copyright © 2020-2023  润新知