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. Cython中def,cdef,cpdef的区别

    这是我的第一篇翻译,希望大家多多给出意见和建议. 如有转载,请注明出处. 原文来自:https://stackoverflow.com/questions/28362009/definition-of ...

  2. 2019-04-10 python入门学习——教材和工具准备

    # 从决定学习编程语言到正式做出计划挤出空余时间,历经一年半,因工作原因及生活原因不断搁浅,从湖北到浙江再回湖北,暂时稳定在一家小公司,从日常加班中压缩时间学习,于此记录学习进度.学习问题,在此过程中 ...

  3. 学习photoshop心得

    简要的学习了ps的三大功能p图,抠图,作图, p图主要是学了换脸这一效果,用到套索工具,把范冰冰的脸接到郭德纲身上, 首先使用套索工具把脸圈起来 然后移动到 另一个人脸上 再然后混合图层,自动混合 差 ...

  4. python七类之列表元组

    列表 一.关键字:  list  lst = [ , , , , , , ,] lst = [1,2,3,4] 二.方法: 1.增加:​ . append( ) #追加​​​,添加元素进列表最后 ls ...

  5. python 装饰器 (多个装饰器装饰一个函数---装饰器前套一个函数)

    #带参数的装饰器 #500个函数 # import time # FLAGE = False # def timmer_out(flag): # def timmer(func): # def inn ...

  6. hdu6370 并查集+dfs

    Werewolf Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 262144/262144 K (Java/Others)Total ...

  7. AVL重平衡细节——插入

    话说这个系列鸽了好久,之前在准备语言考试,就没管博客了,现在暑假咱们继续上路! 每当我们进行一次插入之后,整棵AVL树的平衡性就有可能发生改变,为了控制整棵树的高度,我们需要通过一系列变换(重平衡)来 ...

  8. shell重温---基础篇(shell变量&字符串以及git GUI运行shell脚本方式)

    既然是基础篇那肯定是需要对shell的各种需要注意的基本点进行说明了.接下来就是show time...    shell呢,是一个用C语言编写的应用程序,是用户使用linux的桥梁.所以呢,他既是一 ...

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

        29):1.题目:按相反的顺序输出列表的值. #!/usr/bin/python # -*- coding: UTF-8 -*- a = ['one', 'two', 'three'] for ...

  10. P3527 [POI2011]MET-Meteors

    P3527 [POI2011]MET-Meteors 链接 整体二分! 代码 #include<bits/stdc++.h> using namespace std; typedef lo ...