美文网首页
Context理解

Context理解

作者: 木头猿 | 来源:发表于2018-07-31 15:00 被阅读0次

官方文档

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);

相关文章

  • 源码学习->05Context

    参考文章 : 1. 理解Android Context理解Application创建过程 Context : 1、...

  • Context理解

    官方文档 https://doc.react-china.org/docs/context.html#api 个人...

  • 理解Context

    此文为Android内核剖析学习 Context是啥 一个Context意味着一个场景,一个场景就是用户和操作系统...

  • 理解Context

    什么是Context Context: 字面理解为上下文,语境。Android应用模型是基于组件的应用设计模式,组...

  • 理解Context

    我们平时对Context的理解无外乎两方面: 调用Context的方法,比如启动activity,访问资源; 作为...

  • Context 理解

    继承关系 Context是个抽象类,在加载资源、启动一个Activity、获取系统服务、获取内部文件的路径,及创建...

  • 对 Context 的理解

    对 Context 的理解 1. Context的作用: Context 是应用组件的上下文,有了 Context...

  • HI,Context!

    Context的理解 context的使用场景: getResources() StartActivity() 弹...

  • 进阶之光笔记二

    第五章 理解上下文Context Context的关联类 Context使用场景:1.使用Context调用方法,...

  • context的理解

    转载自:http://blog.csdn.net/singwhatiwanna/article/details/2...

网友评论

      本文标题:Context理解

      本文链接:https://www.haomeiwen.com/subject/tdjqvftx.html