React的context就是一个全局变量,可以从根组件跨级别在React的组件中传递。React context的API有两个版本,React16.x之前的是
老版本的context,之后的是新版本的context。

1.老版本的context

getChildContext 根组件中声明,一个函数,返回一个对象,就是context
childContextTypes 根组件中声明,指定context的结构类型,如不指定,会产生错误
contextTypes 子孙组件中声明,指定要接收的context的结构类型,可以只是context的一部分结构。contextTypes 没有定义,context将是一个空对象。
this.context 在子孙组件中通过此来获取上下文
(注:从React v15.5开始 ,React.PropTypes 助手函数已被弃用,可使用 prop-types 库 来定义contextTypes)

举例如下:

//根组件
class MessageList extends React.Component {
getChildContext() {
return {color: "purple",text: "item text"};
} render() {
const children = this.props.messages.map((message) =>
<Message text={message.text} />
);
return <div>{children}</div>;
}
} MessageList.childContextTypes = {
color: React.PropTypes.string
text: React.PropTypes.string
}; //中间组件
class Message extends React.Component {
render() {
return (
<div>
<MessageItem />
<Button>Delete</Button>
</div>
);
}
} //孙组件(接收组件)
class MessageItem extends React.Component {
render() {
return (
<div>
{this.context.text}
</div>
);
}
} MessageItem.contextTypes = {
text: React.PropTypes.string
}; class Button extends React.Component {
render() {
return (
<button style={{background: this.context.color}}>
{this.props.children}
</button>
);
}
} Button.contextTypes = {
color: React.PropTypes.string
};

2.新版本的context

新版本的React context使用了Provider和Customer模式,和react-redux的模式非常像。在顶层的Provider中传入value,
在子孙级的Consumer中获取该值,并且能够传递函数,用来修改context,如下代码所示:

//创建Context组件
const ThemeContext = React.createContext({
theme: 'dark',
toggle: () => {}, //向上下文设定一个回调方法
}); //运行APP
class App extends React.Component {
constructor(props) {
super(props); this.toggle = () => { //设定toggle方法,会作为context参数传递
this.setState(state => ({
theme:
state.theme === themes.dark
? themes.light
: themes.dark,
}));
}; this.state = {
theme: themes.light,
toggle: this.toggle,
};
} render() {
return (
<ThemeContext.Provider value={this.state}> //state包含了toggle方法
<Content />
</ThemeContext.Provider>
);
}
} //中间组件
function Content() {
return (
<div>
<Button />
</div>
);
} //接收组件
function Button() {
return (
<ThemeContext.Consumer>
{({theme, toggle}) => (
<button
onClick={toggle} //调用回调
style={{backgroundColor: theme}}>
Toggle Theme
</button>
)}
</ThemeContext.Consumer>
);
}

详细用法可以参考官方文档:https://react.docschina.org/docs/context.html#reactcreatecontext

3. context在如下的生命周期钩子中可以使用

constructor(props, context)
componentWillReceiveProps(nextProps, nextContext)
shouldComponentUpdate(nextProps, nextState, nextContext)
componentWillUpdate(nextProps, nextState, nextContext)
componentDidUpdate(prevProps, prevState, prevContext)

4. 在无状态组件中可以通过参数传入

function D(props, context) {
return (
<div>{this.context.user.name}</div>
);
} D.contextTypes = {
user: React.PropTypes.object.isRequired
}

5. React context的局限性

1. 在组件树中,如果中间某一个组件 ShouldComponentUpdate returning false 了,会阻碍 context 的正常传值,导致子组件无法获取更新。
2. 组件本身 extends React.PureComponent 也会阻碍 context 的更新。

注意点:

1. Context 应该是唯一不可变的
2. 组件只在初始化的时候去获取 Context

参考:https://www.tuicool.com/articles/nUryimf
     https://segmentfault.com/a/1190000012575622

React context基本用法的更多相关文章

  1. React Context 的用法

    在React的官方文档中,Context被归类为高级部分(Advanced),属于React的高级API,但官方并不建议在稳定版的App中使用Context. The vast majority of ...

  2. 你不可不知的 React Native 混合用法(Android 篇)

    前言 当前 React Native 虽说版本更新比较快,各种组件也提供的很全面了,但是在某些情况下,混合开发的方式才会快速缩短开发周期,原因无非就是原生平台的"底蕴"无疑更深,拥 ...

  3. React Context API

    使用React 开发程序的时候,组件中的数据共享是通过数据提升,变成父组件中的属性,然后再把属性向下传递给子组件来实现的.但当程序越来越复杂,需要共享的数据也越来越多,最后可能就把共享数据直接提升到最 ...

  4. [React]Context机制

    在React中,Context机制是为了方便在组件树间传递数据. 例子 import React from 'react' const themes={ light:"亮色主题", ...

  5. [React] Prevent Unnecessary Rerenders of Compound Components using React Context

    Due to the way that React Context Providers work, our current implementation re-renders all our comp ...

  6. 探索 Redux4.0 版本迭代 论基础谈展望(对比 React context)

    Redux 在几天前(2018.04.18)发布了新版本,6 commits 被合入 master.从诞生起,到如今 4.0 版本,Redux 保持了使用层面的平滑过渡.同时前不久, React 也从 ...

  7. React Hooks +React Context vs Redux

    React Hooks +React Context vs Redux https://blog.logrocket.com/use-hooks-and-context-not-react-and-r ...

  8. [译]React Context

    欢迎各位指导与讨论 : ) 前言 由于笔者英语和技术水平有限,有不足的地方恳请各位指出.我会及时修正的 O(∩_∩)O 当前React版本 15.0.1 时间 2016/4/25 正文 React一个 ...

  9. React的组件用法

    React.createClass() 中文翻译 https://discountry.github.io/react/3.4K ( https://doc.react-china.org868 ) ...

随机推荐

  1. php post提交xml文件

    <?php header("Content-type: text/xml;"); // xml code demo $xmlData = '<?xml version= ...

  2. 右键添加git-bash

    主要: 右键如果没有git-bash,如何给右键手动添加 前面对右键存在git-bash但使用出现问题的解决,也想到如果右键都没有,该如何给右键添加了,于是接着记录下如何添加的过程: 情形: 手动给右 ...

  3. nginx配置SSL证书/强制跳转与非强制跳转

    支持强制跳转HTTPS server { listen 80; server_name www.test.com; rewrite ^(.*)$ https://${server_name}$1 pe ...

  4. Leecode刷题之旅-C语言/python-83删除排序链表中的重复元素

    /* * @lc app=leetcode.cn id=83 lang=c * * [83] 删除排序链表中的重复元素 * * https://leetcode-cn.com/problems/rem ...

  5. clear()、sync()、ignore()

    #include <iostream> using namespace std; int main() { int a; cin>>a; cout<<cin.rds ...

  6. linux实验-基本指令1

    1.root帐号登录,查看/tmp目录,如果/tmp目录下没有子目录myshare,则建立该目录. 2.创建帐号testuser. 3.把myshare目录及其目录下的所有文件和子目录的拥有者该为te ...

  7. Kubernetes-创建集群(四)

    Kubernetes可以运行在多种平台,从笔记本到云服务商的虚拟机,再到机架上的裸机服务器.要创建一个Kubernetes集群,根据不同的场景需要做的也不尽相同,可能是运行一条命令,也可能是配置自己定 ...

  8. ABAP CDS ON HANA-(4)ヘッダー行編集

    Explicit Name List use in CDS We create a simple  CDS View like below. @AbapCatalog.sqlViewName: ‘ZS ...

  9. python2.7练习小例子(二十八)

    28):题目:请输入星期几的第一个字母来判断一下是星期几,如果第一个字母一样,则继续判断第二个字母.     程序分析:用情况语句比较好,如果第一个字母一样,则判断用情况语句或if语句判断第二个字母. ...

  10. IDA动态调试SO文件

    1. 所需工具 IDA Pro 6.6. 安卓SDK工具 2. 模拟器设置 将ida所在目录的dbgsrv文件夹内的android_server文件push到模拟器中. 设置777属性 启动调试服务器 ...