使用官方提供的方式 公共的上下文对象 类型Vue中 var bus = new Vue() bus.$on bus.$emit
1:新建了一个公共的bus.js 写入如下代码
import React from "react";
const Context = React.createContext();
export default Context;
2:到App.js中引入bus文件
import Child10 from "./Child10";
import Child11 from "./Child11";
import Context from "./bus";
3:在组件调用的地方写入
<Context.Provider value={
{
num:10,
add:function(){
this.num++;
}
}
}>
<Child10></Child10>
<Child11></Child11>
</Context.Provider>
对上面进行解释
4:在回到Child10中 对num进行获取和修改
import React, { Component } from 'react'
import Context from "./bus";
export default class Child10 extends Component {
static contextType = Context;
constructor(props){
super(props);
}
render() {
return (
<div>
我是第十个组件{this.context.num}
<button onClick={
()=>{
this.context.add();
this.forceUpdate();
}
}>加法</button>
</div>
)
}
}
代码解释如下
最后去Child11.js中 代码如下
import React, { Component } from 'react';
import Context from "./bus";
export default class Child11 extends Component {
static contextType = Context;
render() {
return (
<div>
我是第十一个组件<button onClick={()=>{
alert(this.context.num);
}}>获取值</button>
</div>
)
}
}
代码解释
运行就可以看到效果