Context理解

官方文档

https://doc.react-china.org/docs/context.html#api

个人理解

context的使用用到生产者消费者模式,React.createContext创建一对 { Provider, Consumer },Provider需要一个value属性,这个属性能够传递给 Provider 的后代 Consumers。

export const themes = {
  light: {
    foreground: '#ffffff',
    background: '#222222',
  },
  dark: {
    foreground: '#000000',
    background: '#eeeeee',
  },
};
//export 是将该变量导出,这样在其他文件中可以通过import导入
export const ThemeContext = React.createContext(
  themes.dark // 默认值
);

function ThemedButton(props) {
  return (
//使用Context.Consumer
    <ThemeContext.Consumer>
      {theme => (
        <button
          {...props}
          style={{backgroundColor: theme.background}}
        />

      )}
    </ThemeContext.Consumer>
  );
}
// 一个使用到ThemedButton组件的中间组件
function Toolbar(props) {
  return (
    <ThemedButton onClick={props.changeTheme}>
      Change Theme
    </ThemedButton>
  );
}

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      theme: themes.light,
    };

    this.toggleTheme = () => {
      this.setState(state => ({
        theme:
          state.theme === themes.dark
            ? themes.light
            : themes.dark,
      }));
    };
  }

  render() {
    // ThemedButton 位于 ThemeProvider 内
    // 在外部使用时使用来自 state 里面的 theme
    // 默认 dark theme
    return (
      <div>
        //使用Context.Provider,保存了一个theme属性,能够在Context.Consumer中获得该属性
        <ThemeContext.Provider value={this.state.theme}>
          <Toolbar changeTheme={this.toggleTheme} />
        </ThemeContext.Provider>
        //上面的Toolbar 点击事件触发是,该ThemedButton的theme也随之改变
        <ThemeContext.Provider value={this.state.theme}>
          <ThemedButton/>
        </ThemeContext.Provider>
        //该ThemedButton 没有在ThemeContext.Provider中,不能获得theme属性值
          <ThemedButton />
      </div>
    );
  }
}

ReactDOM.render(<App />, document.root);
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,253评论 19 139
  • 通常情况下,在react组件中,我们可以通过props很清楚的知道哪些数据被传递,但是在一些特定的场景下,我们不想...
    feeling_1f11阅读 1,487评论 0 0
  • host Copyright (c) 2014-2017, racaljk. https://github.com...
    JasonStack阅读 3,160评论 0 4
  • May木棉阅读 200评论 0 0
  • 很多人, 只知你的姓, 于是渴慕你的名字。 为何还要去深究? 就像你明白一颗星星的学名, 你也不会关心它是否还在银...
    pinkpen能小勇阅读 212评论 0 0