react的上下文context
react的上下文contex原文链接
context的用法
context的使用基于生产者消费者模式.
- 父节点是生产者,而父节点下的所有节点是消费者.
- 父节点通过一个静态属性childContextTypes 提供给子组件的context对象属性,并实例一个getChildCotext方法,返回一个Context纯对象
- 子组件通过一个静态属性contextTypes声明后,才能访问父组件的context对象属性
父组件 App.js
class App extends Component {
static childContextTypes = {
store: PropTypes.object,
dispatch: PropTypes.func,
subscribe: PropTypes.func,
getStore: PropTypes.func
}
getChildContext() {
const state = {
head:"我是全局head",
body: "我是全局body",
headBtn: "修改head",
bodyBtn: "修改body"
}
const { store,dispatch, subscribe,getStore } = createStore(state,storeChange)
return { store,dispatch,subscribe,getStore}
}
render() {
return (
<div className="App">
<Head />
<Body />
</div>
);
}
}
export default App;
子组件 Body.js
import React, {Component} from 'react';
import Button from '../Button/Button';
import PropTypes from "prop-types";
export default class Body extends Component {
static contextTypes = {
store: PropTypes.object,
subscribe: PropTypes.func,
getStore: PropTypes.func
}
constructor(props) {
super(props);
this.state = {};
}
componentWillMount () {
const { subscribe } = this.context;
this._upState();
subscribe(()=> this._upState())
}
_upState() {
const { getStore } = this.context;
this.setState({
...getStore()
})
}
render () {
return (
<div>
<div className="body">{this.state.body}</div>
<Button/>
</div>
)
}
}
归纳成四步
- childContextTypes =>顶层组件中规定类型
- getChildContext => 顶层组件中设置传递属性
- 子组件通过contextTypes规定数据类型
- 子组件通过this.context获取数据