首页 技术 正文
技术 2022年11月18日
0 收藏 468 点赞 3,886 浏览 1733 个字

一 Context概述

Context provides a way to pass data through the component tree without having to pass props down manually at every level.

Context 提供了一个无需为每层组件手动添加 props,就能在组件树间进行数据传递的方法。

二 项目结构

React Context(一):隐式传递数据

三 代码

1 theme-context.js

import React from 'react';// 主题数据
export const themes = {
gray: {
background: 'gray',
},
gold: {
background: 'gold',
},
};// 创建上下文对象,参数将作为上下文对象的默认值
export const ThemeContext = React.createContext(
themes.gray // default value
);

2 themed-button.js

import React from 'react';
import { ThemeContext } from './theme-context';class ThemedButton extends React.Component {
// props默认是空对象{}。
// context默认是空对象{}。绑定上下文对象后,创建组件时,会传入上下文对象的值(就近原则)。
constructor(props,context){
super(props)
console.log(arguments)
}
render() {
let props = this.props;
let theme = this.context;
return (
<button
{...props}
style={{...theme}} />
)
}
}// 组件类绑定上下文对象后,组件对象的context属性才能使用上下文对象的值(就近原则)。
ThemedButton.contextType = ThemeContext;export default ThemedButton;

3 app.js

import React, { Fragment } from 'react';
import { ThemeContext, themes } from './theme-context';
import ThemedButton from './themed-button';// An intermediate component that uses the ThemedButton
// 工具栏组件(中间件)
function Toolbar(props) {
return (
<ThemedButton onClick={props.changeTheme}>
改变上下文对象
</ThemedButton>
);
}class App extends React.Component {
constructor(props) {
super(props);
this.state = {
theme: themes.gray
};
this.toggleTheme = () => {
this.setState(state => ({
theme: state.theme === themes.gray ? themes.gold : themes.gray
}));
}
} render() {
return (
<Fragment>
{/* 在Provider中,使用Provider提供的值 */}
<ThemeContext.Provider value={this.state.theme}>
<Toolbar changeTheme={this.toggleTheme} />
</ThemeContext.Provider>
{/* 不在Provider中,使用默认值 */}
<section>
<ThemedButton />
</section>
</Fragment>
);
}
}export default App;

4 index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';ReactDOM.render(<App />, document.getElementById('root'));

四 运行效果

1 初始化

React Context(一):隐式传递数据

2 点击按钮

React Context(一):隐式传递数据

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,120
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,592
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,437
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,208
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,844
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,929