[React16]Context

143 阅读1分钟
App.js

import './App.css';
import ThemeContext from "./theme-context";
import ThemeBar from "./components/ThemeBar";


const themes = {
  light: {
      classNames: 'btn - btn-primary',
      bgColor: '#eeeeee',
      color: '#000'
  },
  dark: {
      classNames: 'btn btn-light',
      bgColor: '#222222',
      color: "#fff"
  }
};

class App extends Comment {
  constructor(props) {
    super(props)
    this.state = {
      theme: 'light'
    }
  }

  changeTheme(theme) {
    this.setState({
      theme
    })
  }

  render() {
    const { comments } = this.state
    return (
      <ThemeContext.Provider value={themes[this.state.theme]}>
        <div className="App">
          <header className="App-header">
            <a href="#theme-switcher"
              className="btn btn-light"
              onClick={() => {this.changeTheme('light')}}
            >
              浅色主题
            </a>
            <a href="#theme-switcher"
              className="btn btn-light"
              onClick={() => {this.changeTheme('light')}}
            >
              深色主题
            </a>          
          </header>
          <ThemeBar />
        </div>
      </ThemeContext.Provider>
    )
  }
}

export default App;
theme-context.js

import { createContext } from 'react'

const ThemeContext = 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 } }
            >
              样式区域
              <button className={theme.classNames}>
                样式按钮
              </button>
            </div>
          )
        }
      }
    </ThemeContext.Consumer>
  )
}

export default ThemeBar