一 Context概述

Context provides a way to pass data through the component tree without having to pass props down manually at every level.

Context 提供了一个无需为每层组件手动添加 props,就能在组件树间进行数据传递的方法。

二 项目结构

三 代码

1 theme-context.js

import React from 'react';

// 主题数据
export const themes = {
gray: {
background: 'gray',
},
gold: {
background: 'gold',
},
}; // 创建上下文对象,参数将作为上下文对象的默认值
export const ThemeContext = React.createContext(
themes.gray // default value
);

2 themed-button.js

import React from 'react';
import { ThemeContext } from './theme-context'; class ThemedButton extends React.Component {
// props默认是空对象{}。
// context默认是空对象{}。绑定上下文对象后,创建组件时,会传入上下文对象的值(就近原则)。
constructor(props,context){
super(props)
console.log(arguments)
}
render() {
let props = this.props;
let theme = this.context;
return (
<button
{...props}
style={{...theme}} />
)
}
} // 组件类绑定上下文对象后,组件对象的context属性才能使用上下文对象的值(就近原则)。
ThemedButton.contextType = ThemeContext; export default ThemedButton;

3 app.js

import React, { Fragment } from 'react';
import { ThemeContext, themes } from './theme-context';
import ThemedButton from './themed-button'; // An intermediate component that uses the ThemedButton
// 工具栏组件(中间件)
function Toolbar(props) {
return (
<ThemedButton onClick={props.changeTheme}>
改变上下文对象
</ThemedButton>
);
} class App extends React.Component {
constructor(props) {
super(props);
this.state = {
theme: themes.gray
};
this.toggleTheme = () => {
this.setState(state => ({
theme: state.theme === themes.gray ? themes.gold : themes.gray
}));
}
} render() {
return (
<Fragment>
{/* 在Provider中,使用Provider提供的值 */}
<ThemeContext.Provider value={this.state.theme}>
<Toolbar changeTheme={this.toggleTheme} />
</ThemeContext.Provider>
{/* 不在Provider中,使用默认值 */}
<section>
<ThemedButton />
</section>
</Fragment>
);
}
} export default App;

4 index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App'; ReactDOM.render(<App />, document.getElementById('root'));

四 运行效果

1 初始化

2 点击按钮

最新文章

  1. Eclipse中.calsspath文件解析
  2. SQL Server 诊断查询-(2)
  3. OMXplayer播放视频的参数说明
  4. into outfile 生成sql脚本
  5. Http中Cookie和Session介绍
  6. 在springmvc中controller的一个方法处理多个不同请求
  7. C#Windows Form简易计算器实现(上)
  8. UVa 990 - Diving for Gold
  9. echarts中视觉映射器(visualMap)与时间轴(timeline)混用的实现方法
  10. python 字典实现简单购物车
  11. flume安装
  12. Linux 环境下 Git 安装与基本配置
  13. WebView 安全之 addJavascriptInterface
  14. linux ip命令和ifconfig命令
  15. String对象的属性和方法
  16. HTML5 video 播放视频黑屏
  17. 什么是SPU、SKU、ARPU
  18. 《大型分布式网站架构》学习笔记--01SOA
  19. Gym - 100548G The Problem to Slow Down You
  20. Python 装饰器入门(下)

热门文章

  1. 开发中经常遇到SVN清理失败的问题:
  2. MySQL数据库-pymysql模块操作数据库
  3. Struts2-052 RCE CVE-2017-9805
  4. 学习笔记TF038:实现估值网络
  5. 自己写一个 Hash 表
  6. mysql: 查看某库表大小
  7. Delphi 10-10.2.2启动提示JS错误的解决办法
  8. 树莓派apt-get The value &#39;\stable&#39; is invalid for APT 错误
  9. java使用jdbc连接oracle(其他数据库类似)
  10. Python-实列