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:在组件调用的地方写入

               

                    
                    

                

对上面进行解释

18React子组件使用Context来进行通信_第1张图片

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 (
            
我是第十个组件{this.context.num}
) } }

代码解释如下

18React子组件使用Context来进行通信_第2张图片

最后去Child11.js中 代码如下

import React, { Component } from 'react';
import Context  from  "./bus";

export default class Child11 extends Component {
    static contextType = Context;
    render() {
        return (
            
我是第十一个组件
) } }

代码解释

18React子组件使用Context来进行通信_第3张图片

运行就可以看到效果

你可能感兴趣的:(React)