React context基本用法
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基本用法的更多相关文章
- React Context 的用法
在React的官方文档中,Context被归类为高级部分(Advanced),属于React的高级API,但官方并不建议在稳定版的App中使用Context. The vast majority of ...
- 你不可不知的 React Native 混合用法(Android 篇)
前言 当前 React Native 虽说版本更新比较快,各种组件也提供的很全面了,但是在某些情况下,混合开发的方式才会快速缩短开发周期,原因无非就是原生平台的"底蕴"无疑更深,拥 ...
- React Context API
使用React 开发程序的时候,组件中的数据共享是通过数据提升,变成父组件中的属性,然后再把属性向下传递给子组件来实现的.但当程序越来越复杂,需要共享的数据也越来越多,最后可能就把共享数据直接提升到最 ...
- [React]Context机制
在React中,Context机制是为了方便在组件树间传递数据. 例子 import React from 'react' const themes={ light:"亮色主题", ...
- [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 ...
- 探索 Redux4.0 版本迭代 论基础谈展望(对比 React context)
Redux 在几天前(2018.04.18)发布了新版本,6 commits 被合入 master.从诞生起,到如今 4.0 版本,Redux 保持了使用层面的平滑过渡.同时前不久, React 也从 ...
- React Hooks +React Context vs Redux
React Hooks +React Context vs Redux https://blog.logrocket.com/use-hooks-and-context-not-react-and-r ...
- [译]React Context
欢迎各位指导与讨论 : ) 前言 由于笔者英语和技术水平有限,有不足的地方恳请各位指出.我会及时修正的 O(∩_∩)O 当前React版本 15.0.1 时间 2016/4/25 正文 React一个 ...
- React的组件用法
React.createClass() 中文翻译 https://discountry.github.io/react/3.4K ( https://doc.react-china.org868 ) ...
随机推荐
- php中处理中文的注意
使用session的情况下------------------------- php.ini register_globals = Off 保持关闭,开启可能会导致iconv转换中文产生错误 修改ph ...
- 修复网站漏洞对phpmyadmin防止被入侵提权的解决办法
phpmyadmin是很多网站用来管理数据库的一个系统,尤其是mysql数据库管理的较多一些,最近phpmysql爆出漏洞,尤其是弱口令,sql注入漏洞,都会导致mysql的数据账号密码被泄露,那么如 ...
- linux文件操作篇 (四) 目录操作
#include <sys/stat.h>#include <unistd.h>#include <dirent.h> //创建文件夹 路径 掩码 int mkdi ...
- POJ1985 树的直径(BFS
Cow Marathon Description After hearing about the epidemic of obesity in the USA, Farmer John wants ...
- 【POJ】1008 Maya Calendar
参考:https://blog.csdn.net/u011392408/article/details/28866779 https://blog.csdn.net/qq_36424540/artic ...
- 再谈js传值和传址
js的传值和传址还是真绕,前回文说道 1.值类型是传值的 2.对象和数组是传址的 这两点通过例子的到了证实 然而还有一种情况没有讨论 即 函数的参数的传值和传址 通过实验,在函数中用一个新对象去覆盖传 ...
- mock.js中新增测试接口无效,返回404
项目是使用的npm+vue+mock模拟数据 我碰到的是在mock配置文件中新增接口,但是接口在测试时无效,返回404.但是在前端代码中把新接口换成配置文件中之前就有的,然后测试就正常了. 所以按问题 ...
- CCF-NOIP-2018 提高组(复赛) 模拟试题(九)(2018 CSYZ长沙一中)
T1 Circle [问题描述] 小 w 的男朋友送给小 w 一个 n 个点 m 条边的图,并且刁难小 w 要她找出点数最少的正环. 小 w 不会做,于是向你求助. [输入格式] 第一行两个整数\(n ...
- Spring实战第五章学习笔记————构建Spring Web应用程序
Spring实战第五章学习笔记----构建Spring Web应用程序 Spring MVC基于模型-视图-控制器(Model-View-Controller)模式实现,它能够构建像Spring框架那 ...
- Web负载均衡技术
Web负载均衡(Load Balancing),简单地说就是给我们的服务器集群分配“工作任务”,而采用恰当的分配方式,对于保护处于后端的Web服务器来说,非常重要. 负载均衡的策略有很多,我们从简单的 ...