react-context

import React from 'react';
const themes = {
  light: {
    foreground: '#ffffff',
    background: '#222222'
  },
  dark: {
    foreground: '#000000',
    background: '#eeeeee'
  }
};
const ThemeContext = React.createContext({
  theme: themes.light,
  toggleTheme: () => {}
});
function ThemeTogglerButton() {
  return (
    
      {({theme, toggleTheme}) => (
        
      )}
    
  );
}

class App extends React.Component {
  constructor(props) {
    super(props);

    this.toggleTheme = () => {
      this.setState(state => ({
        theme:
          state.theme === themes.dark
            ? themes.light
            : themes.dark
      }));
    };
    // State 包含了 updater 函数 所以它可以传递给底层的 context Provider
    this.state = {
      theme: themes.dark,
      toggleTheme: this.toggleTheme
    };
  }

  render() {
    // 入口 state 传递给 provider
    return (
      
        
      
    );
  }
}

function Content(props) {
  return (
    
{props.test.theme.foreground}
); } export default App

你可能感兴趣的:(react-context)