利用context组件数据传递
react的数据传递 是从父级向子级传递的。通过props。如果是很多组件需要的数据,通过props传递会非常麻烦。这个时候可以使用context。
context需要可以类似于store但是也不能滥用。
context适用场景:地区偏好,UI主题
传统实现:

class App extends React.Component {
render() {
return <Toolbar theme="dark" />;
}
}
function Toolbar(props) {
// Toolbar 组件接受一个额外的“theme”属性,然后传递给 ThemedButton 组件。
// 如果应用中每一个单独的按钮都需要知道 theme 的值,这会是件很麻烦的事,
// 因为必须将这个值层层传递所有组件。
return (
<div>
<ThemedButton theme={props.theme} />
</div>
);
}
class ThemedButton extends React.Component {
render() {
return <Button theme={this.props.theme} />;
}
}
创建context对象
const MyContext = React.createContext(defaultValue);
创建一个context对象。设置默认值。
当 React 渲染一个订阅了这个 Context 对象的组件,这个组件会从组件树中离自身最近的那个匹配的 Provider 中读取到当前的 context 值。如果没有Provider就会取默认值。
context.Provider
<MyContext.Provider value={默认值}>
每个context对象都返回一个provider组件
一个provider组件可以和多个消费组件对应关系。
<ThemeContext.Provider value="dark">
<Toolbar />
<ContextTypePage /> //多个组件
</ThemeContext.Provider>
多个provider也可以嵌套,里层会覆盖外层。
import {ThemeContext, UserContext} from "../Context";
export default function UseContextPage(props) {
const themeContext = useContext(ThemeContext);
const { themeColor } = themeContext;
const userContext = useContext(UserContext);
return (
<div className="border">
<h3 className={themeColor}>UseContextPage</h3>
<p>{userContext.name}</p>
</div>
);
}
provider值变化 里面所有的消费组件都会渲染。
组件的contextType属性
挂载在 class 上的 contextType 属性会被重赋值为一个 Context 对象。这能让你使用 this.context 来消费最近 Context 上的那个值。你可以在任何生命周期中访问到它。
import {ThemesContext} from './theme-context'
export class ThemedButton extends React.Component{
render(){
let props =this.props;
let theme =this.context;
console.log(theme)
return (
<button
{...props}
style={{backgroundColor:theme.background,color:theme.foreground,width:"200px"}}
/>
)
}
}
ThemedButton.contextType=ThemesContext;//这个一定要有
简单的例子:
context实现:
// Context 可以让我们无须明确地传遍每一个组件,就能将值深入传递进组件树。
// 为当前的 theme 创建一个 context(“light”为默认值)。
const ThemeContext = React.createContext('light');
class App extends React.Component {
render() {
// 使用一个 Provider 来将当前的 theme 传递给以下的组件树。
// 无论多深,任何组件都能读取这个值。
// 在这个例子中,我们将 “dark” 作为当前的值传递下去。
return (
<ThemeContext.Provider value="dark">
<Toolbar />
</ThemeContext.Provider>
);
}
} // 中间的组件不必指明往下传递 theme 。
function Toolbar() {
return (
<div>
<ThemedButton />
</div>
);
} class ThemedButton extends React.Component {
// 指定 contextType 读取当前的 theme context。
// React 会往上找到最近的 theme Provider,然后使用它的值。
// 在这个例子中,当前的 theme 值为 “dark”。
static contextType = ThemeContext;
render() {
return <Button theme={this.context} />;
}
}
实际应用:
theme-context.js
import React from 'react';
export const themes={
light:{
foreground: '#ffffff',
background:"#4DB8C6"
},
dark:{
foreground: '#ffffff',
background:"#222222"
}
}
export const ThemesContext =React.createContext(themes.dark)
themed-button.js
import React from 'react';
import {ThemesContext} from './theme-context' export class ThemedButton extends React.Component{
render(){
let props =this.props;
let theme =this.context;
console.log(theme)
return (
<button
{...props}
style={{backgroundColor:theme.background,color:theme.foreground,width:"200px"}}
/>
)
}
}
ThemedButton.contextType=ThemesContext;
app.js
function ToolBar1(props){
return (
<ThemedButton onClick={props.changeTheme}>
主题按钮
</ThemedButton>
)
}
class App extends React.Component{
constructor(props){
super(props);
this.state={
theme:themes.light
}
this.toggleTheme = () => {
this.setState(state => ({
theme:
state.theme === themes.dark
? themes.light
: themes.dark,
}));
console.log(this.state.theme)
};
}
render (){
return (
<ThemesContext.Provider value={this.state.theme}>
<ToolBar1 changeTheme={this.toggleTheme} />
</ThemesContext.Provider>
)
}
}
效果图

最好实现主题变动的是 改变类名
写两套css样式 根据不同的类名 进行处理。
react官网 https://react.docschina.org/docs/context.html#when-to-use-context
利用context组件数据传递的更多相关文章
- vue教程3-05 vue组件数据传递、父子组件数据获取,slot,router路由
vue教程3-05 vue组件数据传递 一.vue默认情况下,子组件也没法访问父组件数据 <!DOCTYPE html> <html lang="en"> ...
- React中父子组件数据传递
Vue.js中父子组件数据传递:Props Down , Events Up Angular中父子组件数据传递:Props Down, Events Up React中父子组件数据传递:Prop ...
- 利用 postMessage 进行数据传递 (iframe 及web worker)及问题
一 postMessage应用于主页面和iframe之间进行数据的传递 1 子iframe页面向主页面进行数据传递: // 多个子iframe需要将自己的计数统计到主页面进行数据上报 window. ...
- vue 组件数据传递
vue组件化开发 主要为了把一个大功能拆分成若干个小的功能,解决高耦合问题,同时也方便开发人员维护. 从功能上组件可以分为木偶组件和功能组件. 木偶组件(为了接收数据,渲染数据,基本上是没有逻辑的 ...
- Android开发探秘之四:利用Intent实现数据传递
在Android开发过程中,很多人都熟悉Intent,这是个用于在多个View之间共享数据的类.本节主要是继承上节,通过点选ListView中的文本,把文本中的URL加载到一个新的页面上,并且打印出来 ...
- Vue2.x中的父组件数据传递至子组件
父组件结构 template <template> <div> <v-girl-group :girls="aGirls"></v-gir ...
- vue2.0 父子组件数据传递prop
vue的一个核心概念就是组件,而组件实例的作用域是孤立的,所以组件之间是不能直接引用其他组件的数据的.极端点举例来说,就是可以在同一个项目中,每一个组件内都可以定义相同名称的数据. data () { ...
- Vue2.x之父子组件数据传递
父传子,并且通过fatherEvent接收子组件传过来的值 <template> <div class='father'> <Son :fatherData=" ...
- react父子组件数据传递
子传父 1.首先父组件设定一个自定义函数 getChildDatas = (values) => { //...业务代码 } 2.将该函数暴露在子组件的引用上 <Child getChil ...
- 关于vue.js父子组件数据传递
vue.js中使用props down,events up的原则进行父子组件间的通信,先来记录下props down,看个例子: <div id="app2"> < ...
随机推荐
- OnionArch 2.0 - 基于DDD的洋葱架构改进版开源
大家好,去年我发布了一篇 OnionArch - 采用DDD+CQRS+.Net 7.0实现的洋葱架构.很多程序员都比较感兴趣,给我要源代码.这次我把OnionArch进行了升级,改进了一些特性,并放 ...
- 使用 flexible.js + rem 制作苏宁移动端首页
一.技术选型 二.搭建相关文件夹 三.设置视口标签以及引入初始化样式文件和js文件 四.body 样式 五.rem 适配方案二 body样式修改 index.css body { min-width: ...
- JSP第四次作业
1. 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8&q ...
- Hystrix断路器
1.介绍 ①产生原因 服务雪崩: 多个微服务之间调用,假设A调用B,C,B和C又调用其他微服务,这就是扇出. 如果扇出的链路上有某个微服务调用响应时间过长或者不可用,那么A调用会占用越来越多的系统资源 ...
- git文件管理
一.概念: git:分布式的版本管理工具Gitee(码云):是开源中国社区推出的代码托管协作开发平台,支持Git和SVN,提供免费的私有仓库托管.Gitee专为开发者提供稳定.高效.安全的云端软件开发 ...
- 【GDKOI 2021提高组DAY2】抄写
\(\text{Solution}\) \(dp\) 翻折就只需预处理回文中心 \(Manacher\) 预处理即可 \(Code\) #include<cstdio> #include& ...
- JZOJ 4253.QYQ在艾泽拉斯
\(\text{Problem}\) 有向不联通图,求每个子图至多选出一条最大权值和的路径,求前 \(k+1\) 个 \(\text{Solution}\) 显然将每个子图缩点后 \(dp\),排序 ...
- JAVASE小练习 (今天做一个基于javase的银行ATM小练习)
实现的功能有1,用户登录2,用户开户(基于用户登录)3,查询账户(基于用户登录)4,存款5,取款6,转账7,修改密码(只有三次确认密码的机会)8,退出登录9,注销 这个小例子可以让我们充分复习所学的j ...
- postgresql序列基本操作
1.创建序列 CREATE SEQUENCE if not exists test_mergetable_id_seq INCREMENT 1 MINVALUE 1 MAXVALUE 99999999 ...
- Laravel 框架根据经纬度计算在一定距离内的数据
$model = DB::table('table_name'); public static function scope_distance($model, $from_latitude, $fro ...