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 ...
随机推荐
- 【SQL Server】SQL Server占用CPU使用率100%的解决方法
原文:[SQL Server]SQL Server占用CPU使用率100%的解决方法 近日,帮一个客户解决了服务器CPU占用率高达100%的问题. 以前做的一个某污水处理厂自控系统项目,客户反映其自控 ...
- OSChina 周三乱弹 —— 致力于做一名优秀的女程序员鼓励师
https://my.oschina.net/xxiaobian/blog/848096
- Sysinternals套件2016年11月更新发布,诸多工具被更新
Sysinternals 实用程序可帮助您管理.解决和诊断 Windows 系统和应用程序,在 Sysinternals 的 2016 年 11 月更新中,微软增强 在 sysmon 对注册表和文件事 ...
- QTableWidget简单应用之文件浏览器
实现下面这个简单的文件浏览功能,常用的QTableWidget设置都用到了. 基本设置 ui->tableWidget->setColumnCount(5); //设置表格列数 ui- ...
- Mariadb的安装与使用
一.安装Mariadb 参考博客:https://www.cnblogs.com/pyyu/p/9467289.html 安装软件的三中方式 yum原码编译安装下载rpm安装 yum与原码编译安装安装 ...
- ABP开发框架前后端开发系列---(8)ABP框架之Winform界面的开发过程
在前面随笔介绍的<ABP开发框架前后端开发系列---(7)系统审计日志和登录日志的管理>里面,介绍了如何改进和完善审计日志和登录日志的应用服务端和Winform客户端,由于篇幅限制,没有进 ...
- Spring Boot:整合Spring Security
综合概述 Spring Security 是 Spring 社区的一个顶级项目,也是 Spring Boot 官方推荐使用的安全框架.除了常规的认证(Authentication)和授权(Author ...
- ASP.NET Core中GetService()和GetRequiredService()之间的区别
上篇文章<在.NET Core 3.0中的WPF中使用IOC图文教程>中,我们尝试在WPF中应用.NET Core内置的IOC进行编程,在解析MainWindow的时候我用了GetRequ ...
- 【LEETCODE】32、LeetCode的第35题,查找插入的位置
凉凉,看来想做好一个题还不容易啊... 有点难受... 1.看看题目吧 Given a sorted array and a target value, return the index if the ...
- 【commons-lang3工具】JAVA脱敏工具
前言:commons-langbao中有很多方便的工具,无需我们自己去实现,能够节省很多开发时的问题: 1.工具包,引入依赖,jDK8对应的版本如下: <!-- https://mvnrepos ...