React的Context的使用方法简介
context
定义: Context提供了一种方式,能够让数据在组件树中传递,而不必一级一级手动传递。
API : createContext(defaultValue?)。
使用方法:
首先要引入createContext
import React, { Component, createContext } from 'react';
然后创建一个Context
const BatteryContext = createContext();
然后用BatteryContext.Provider包裹组件并且传递属性值。
<BatteryContext.Provider value={60}>
<Middle /> //子组件
</BatteryContext.Provider>
为了方便看出效果,将定义一个子组件和一个孙组件。然后不通过子组件,孙组件直接取值。
import React, { Component, createContext } from 'react';
const BatteryContext = createContext();
//声明一个孙组件
class Leaf extends Component {
render() {
return (
)
}
}
//声明一个子组件
class Middle extends Component {
render() {
return <Leaf />
}
}
class App extends Component {
render(){
return (
<BatteryContext.Provider value={60}>
<Middle />
</BatteryContext.Provider>
);
}
}
export default App;
孙组件需要BatteryContext.Consumer来接收值,Consumer里面不能直接渲染其他组件,而是要声明一个函数。函数的参数就是context的值。
class Leaf extends Component {
render() {
return (
<BatteryContext.Consumer>
{
battery => <h1>Battery : {battery}</h1>
}
</BatteryContext.Consumer>
)
}
}
效果图;

这样没通过Middle组件来传递值,但是Leaf组件能通过context来获得属性。这就是context的基本用法。
state = {
battery: 60
}
render() {
const { battery } = this.state;
return (
<BatteryContext.Provider value={battery}>
<button
type="button"
onClick={() => this.setState({ battery: battery - 1 })}
>
减减
</button>
<Middle />
</BatteryContext.Provider>
);
}
import React, { Component, createContext } from 'react';
const BatteryContext = createContext();
//声明一个孙组件
class Leaf extends Component {
render() {
return (
<BatteryContext.Consumer>
{
battery => <h1>Battery : {battery}</h1>
}
</BatteryContext.Consumer>
)
}
}
//声明一个子组件
class Middle extends Component {
render() {
return <Leaf />
}
}
class App extends Component {
state = {
battery: 60
}
render() {
const { battery } = this.state;
return (
<BatteryContext.Provider value={battery}>
<button
type="button"
onClick={() => this.setState({ battery: battery - 1 })}
>
减减
</button>
<Middle />
</BatteryContext.Provider>
);
}
}
export default App;
效果图:

这样每次点击都会使battery得数值发生变化,从而重渲染Consumer下面的元素。
const OnLineContext = createContext();
class App extends Component {
state = {
battery: 60,
online: false
}
render() {
const { battery, online } = this.state;
return (
<BatteryContext.Provider value={battery}>
<OnLineContext.Provider value={online} >
<button
type="button"
onClick={() => this.setState({ battery: battery - 1 })}
>
减减
</button>
<button
type="button"
onClick={() => this.setState({ online: !online })}
>
Switch
</button>
<Middle />
</OnLineContext.Provider>
</BatteryContext.Provider>
);
}
class Leaf extends Component {
render() {
return (
<BatteryContext.Consumer>
{
battery => (
<OnLineContext.Consumer>
{
online => <h1>Battery : {battery} , Online : {online.toString()}</h1>
}
</OnLineContext.Consumer>
)
}
</BatteryContext.Consumer>
)
}
}
全部代码:
import React, { Component, createContext } from 'react';
const BatteryContext = createContext();
const OnLineContext = createContext();
//声明一个孙组件
class Leaf extends Component {
render() {
return (
//与Provider类似。Consumer也需要嵌套,顺序不重要。只要Consumer需要声明函数,所以要注意语法。
<BatteryContext.Consumer>
{
battery => (
<OnLineContext.Consumer>
{
online => <h1>Battery : {battery} , Online : {online.toString()}</h1>
}
</OnLineContext.Consumer>
)
}
</BatteryContext.Consumer>
)
}
}
//声明一个子组件
class Middle extends Component {
render() {
return <Leaf />
}
}
class App extends Component {
state = {
battery: 60,
online: false
}
render() {
const { battery, online } = this.state;
//接下来声明online的Provider了。如果有多个context变量的话,只需要把Privider嵌套进来即可,顺序不重要。
return (
<BatteryContext.Provider value={battery}>
<OnLineContext.Provider value={online} >
<button
type="button"
onClick={() => this.setState({ battery: battery - 1 })}
>
减减
</button>
<button
type="button"
onClick={() => this.setState({ online: !online })}
>
Switch
</button>
<Middle />
</OnLineContext.Provider>
</BatteryContext.Provider>
);
}
}
export default App;
效果图:

const BatteryContext = createContext(30);
React的Context的使用方法简介的更多相关文章
- React的contextType的使用方法简介
上一篇介绍了Context的使用方法.但是Context会让组件变得不纯粹,因为依赖了全局变量.所以这决定了Context一般不会大规模的使用.所以一般在一个组件中使用一个Context就好. 由于C ...
- iOS中常用的四种数据持久化方法简介
iOS中常用的四种数据持久化方法简介 iOS中的数据持久化方式,基本上有以下四种:属性列表.对象归档.SQLite3和Core Data 1.属性列表涉及到的主要类:NSUserDefaults,一般 ...
- 手写一个React-Redux,玩转React的Context API
上一篇文章我们手写了一个Redux,但是单纯的Redux只是一个状态机,是没有UI呈现的,所以一般我们使用的时候都会配合一个UI库,比如在React中使用Redux就会用到React-Redux这个库 ...
- 网络神器Greasemonkey(油猴子)使用方法简介+脚本分享【转载】
推荐下,觉得这个方法有用, 今天艾薇百科来介绍一下功能强大的Greasemonkey,俗称"油猴子",Greasemonkey可以自由定制网页,实现你想要的各种功能.堪称" ...
- Redis Cluster搭建方法简介22211111
Redis Cluster搭建方法简介 (2013-05-29 17:08:57) 转载▼ Redis Cluster即Redis的分布式版本,将是Redis继支持Lua脚本之后的又一重磅 ...
- Monte Carlo方法简介(转载)
Monte Carlo方法简介(转载) 今天向大家介绍一下我现在主要做的这个东东. Monte Carlo方法又称为随机抽样技巧或统计实验方法,属于计算数学的一个分支,它是在上世纪四十年代 ...
- C#——Marshal.StructureToPtr方法简介
目录 MarshalStructureToPtr方法简介 功能及位置 语法 参数说明 异常 备注 举例 本博客(http://blog.csdn.net/livelylittlefish)贴出作者(三 ...
- Fatal error: Using $this when not in object context in 解决方法
Fatal error: Using $this when not in object context in 解决方法 粗心造成的错误 $this 只存在于下面情况 $obj = new object ...
- TabBarController创建及使用方法简介
TabBarController创建及使用方法简介 大致讲解一下TabBarController的创建过程: 首先,我们需要一些视图,如创建UIControllerView类型的view1,view2 ...
随机推荐
- Failed to recover corrupt cache entry
RangeError java.lang.RuntimeException: ERROR: Failed to recover corrupt cache entry at com.sun.deplo ...
- 利用BLCR加速android的启动(android4.2)
BOSS要求提高安卓系统的启动速度,优化bootloader和kernel后,发现还是达不到要求,没办法才打起zygote的注意. ================================== ...
- Windows下获取逻辑cpu数量和cpu核数量
代码可在Windows NT下正常运行 具体API说明请参照如下文档: GetLogicalProcessorInformation 点击打开链接 点击打开链接 点击打开链接 typedef BOOL ...
- cStor云存储、cProc云处理、cVideo云视频、cTrans云传输,云创个人网盘
http://www.cstor.cn,微信公众号:cstor_cn. 云创大数据是国际上云计算产品线齐全的企业之一,针对爆炸式增长的大数据需求,研发了自主知识产权的cStor云存储.cPr ...
- 注册表Demo
一.获取安装程序信息 #include <windows.h> #include <iostream> #include <string> #include < ...
- 客服端JavaScript线程模型
JavaScript语言核心并不包含任何线程机制,并且客服端JavaScript传统上没有定义任何线程机制.HTML5定义了一种作为后台线程的“WebWorker",但是客服端JavaScr ...
- mybatis链接数据库
DBTools类 public class DBTools { // 加载mybatis文件 public static SqlSession getSession() { //加载配置文件 Inpu ...
- 30411MySQL安装与配置_win10
1 下载 1.1下载地址 下载地址 https://downloads.mysql.com/archives/community/ 1.2 选择适合自己的版本并下载 1.3 将下载文件解压至自定义路 ...
- spring 5.x 系列第5篇 —— 整合 mybatis + druid 连接池 (xml配置方式)
源码Gitub地址:https://github.com/heibaiying/spring-samples-for-all 项目目录结构 1.创建maven工程,除了Spring基本依赖外,还需要导 ...
- 【Shell学习笔记3》实践项目自动部署脚本】shell中获取返回值、获取当前sh文件路径
原创部分: 1.获取返回值 #This is a shell to Deploy Project #!/bin/bashcheck_results=`ps -ef | grep "java& ...