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 ) ...
随机推荐
- h5移动端页面meta标签
<!DOCTYPE html> <!-- 使用 HTML5 doctype,不区分大小写 --> <html lang="zh-cmn-Hans"&g ...
- PHP Laravel 5.4 环境搭建
1.php运行环境搭建 在win10系统上进行搭建的,使用的是wamp环境 wampserver3_x86_apache2.4.17_mysql5.7.9_php5.6.15.exe,安装包中集成了 ...
- 计蒜客-----跳跃游戏(C语言)
/********************************************************给定一个非负整数数组,假定你的初始位置为数组第一个下标.数组中的每个元素代表你在那个位 ...
- DESCRIBEFIELD
実行時データ型識別.略語は RTTI です.プログラム実行時にデータ型を識別して処理を行う仕組みです.. DESCRIBE FIELD命令を使用 DESCRIBE FIELD命令を使用して.変数のデー ...
- Druid单机环境安装指南
1.下载单机环境必备工具 下载druid-0.10.1-bin.tar.gz和tranquility-distribution-0.8.2.tgz插件 http://druid.io/download ...
- js获取浏览器内容宽高(小计)
<SCRIPT LANGUAGE="JavaScript">var s = "";s += "\r\n网页可见区域宽:"+ d ...
- windows10安装liux系统
1.前言 因为大部分服务器都是linux系统,需要掌握linux命令行和熟悉linux环境,所以自己用为数不多的工资买了新电脑,就是为了学习linux系统,此文是为了记载自己在windows系统上安装 ...
- 再见NullPointerException。在Kotlin里null的处理(KAD 19)
作者:Antonio Leiva 时间:Apr 4, 2017 原文链接:https://antonioleiva.com/nullity-kotlin/ 关于Kotlin最重要的部分之一:无效处理, ...
- Python网络编程(基础总结、 入门经典)
Linux下文件类型: bcd -lsp b(块.设备文件) c(字符设备文件) d(目录) -(普通文件) ...
- CSP201509-1:数组分段
引言:CSP(http://www.cspro.org/lead/application/ccf/login.jsp)是由中国计算机学会(CCF)发起的“计算机职业资格认证”考试,针对计算机软件开发. ...