18React子组件使用Context来进行通信

使用官方提供的方式 公共的上下文对象  类型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>
        )
    }
}

代码解释

运行就可以看到效果

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值