context
1.组件创建上下文之后,上下文中的数据会被所有的后代组件共享
2.组件依赖上下文,会导致组建不再纯粹依赖state和props
旧的api
创建上下文
只有类组件才可以创建上下文
1.给类组件书写静态属性childContextTypes
,使用该属性对上下文中的数据类型进行约束
2.添加实例方法 getChildContext
,该方法返回的对象,即为上下文中的数据,该数据必须满足类型的约束,该方法会在每次render
之后运行。
const types = {
a: PropTypes.number,
b: PropTypes.string
};
export default class OldContext extends React.Component {
static childContextTypes = types;
state = {
a: 0
};
getChildContext() {
console.log("获取context");
return {
a: 111,
b: "abc"
};
}
render() {
return (
<div>
<p>hello word</p>
<button
onClick={
() => {
this.setState({
a: this.state.a + 1
});
}}
>
click
</button>
</div>
);
}
}
经测试发现,
getChildContext
方法是在render
函数执行之后触发
使用上下文中的数据
要求:组件使用上下文中的数据,组件中必须有一个静态属性contextTypes
,该属性描述了上下文中需要使用的数据类型
获取:1.可以在组件的构造函数中,通过第二参数,获取上下文数据;
2.从组件的context属性中获取(this.context)
3. 函数组件中,通过第二参数获取上下文
// 函数组件的获取方式
function ChildA(props, context) {
return (
<div>
<h1>我是组件childA</h1>
<p>content中的a:{
context.a}</p>
<ChildB />
</div>
);
}
ChildA.contextTypes = {
a: types.a
};
// 类组件的两种方式:
// 1.直接通过this.context属性获取
class ChildB extends React.Component {
static contextTypes = types;
render() {
return (
<div>
<h1>我是组件B</h1>
<p>content中的a:{
this.context.a}</p>
<p>content中的b:{
this.context.b}</p>