奋发图强学 React 系列 (一):React 组件通信

今天上午主要学习了两种 React 组件通信的方式:

方式一:props 和 callBack 方式

可以称为最基本的通信方式,父组件可以通过 props 将信息传递给子组件,子组件可以通过执行 props 中的回调函数(callBack)来触发父组件的方法,实现父与子组件通信。

示例 demo 如下:

jsx 复制代码
import React, { useState, useEffect } from "react";
/**
 * 父子组件之间通信方式 1:props 和 callback 的方式
 */
//
function Son(props) {
  const {fatherSay, sayFather} = props;
  return (
    <div className="son">
      我是子组件
      <div>父组件对我说:{fatherSay}</div>
      <div>我对父组件说:<input type="text" onChange={e => sayFather(e.target.value)}/></div>
    </div>
  )
}

function Father() {
  const [childSay, setChildSay] = useState('');
  const [fatherSay, setFatherSay] = useState('');

  return (
    <div className="father">
      我是父组件
      <div>子组件对我说:{childSay}</div>
      <input type="text" onChange={e => setFatherSay(e.target.value)} />
      <Son fatherSay={fatherSay} sayFather={setChildSay} />
    </div>
  )
}

export default Father;

方式二:eventBus 总线

eventBus 是一个事件发布订阅的轻量级工具库,来源于 Android 事件发布。

eventBus 大致流程如下:

A 模块通过 on 向 EventBus 中注册事件 callBack

B 模块通过 emit 触发 A 模块中的事件 callBack,并传递参数,实现 B -> A 的通信流程

首先用 js 实现一个 eventBus

js 复制代码
class eventBus {
  event = {};
  on(eventName, callBack) {
    if (this.event[eventName]) {
      this.event[eventName].push(callBack);
    } else {
      this.event[eventName] = [callBack];
    }
  }

  emit(eventName, ...args) {
    if (this.event[eventName]) {
      this.event[eventName].forEach((callBack) => {
        callBack(...args);
      });
    }
  }

  off(eventName) {
    if (this.event[eventName]) {
      delete this.event[eventName];
    }
  }
}

export default new eventBus();

接下来可以通过这个 eventBus 实现 React 中的通信

jsx 复制代码
import React, { useState, useEffect } from "react";
import BusService from './eventBus';
/**
 * 父子组件之间通信的方式二:eventBus 事件总线
 */

function Son2() {
  const [fatherSay, setFatherSay] = useState('');
  useEffect(() => {
    BusService.on('fatherSay', (value) => {
      setFatherSay(value)
    })
    return function() {
      BusService.off('fatherSay')
    }
  }, [])
  return <div className="son">
    我是子组件
    父组件对我说:{fatherSay}
    <div>
      我对父组件说:
      <input type="text" onChange={e => BusService.emit('childSay', e.target.value)} />
    </div>
  </div>
}

function Father2() {
  const [childSay, setChildSay] = useState('');
  useEffect(() => {
    BusService.on('childSay', (value) => {
      setChildSay(value);
    })
    return function() {
      BusService.off('childSay')
    }
  }, [])
  return <div className="father">
    我是父组件
    子组件对我说:{childSay}
    <div>
      我对子组件说:
      <input type="text" onChange={e => BusService.emit('fatherSay', e.target.value)} />
    </div>
    <Son2 />
  </div>
}

export default Father2;
相关推荐
清岚_lxn3 小时前
原生SSE实现AI智能问答+Vue3前端打字机流效果
前端·javascript·人工智能·vue·ai问答
ZoeLandia4 小时前
Element UI 设置 el-table-column 宽度 width 为百分比无效
前端·ui·element-ui
橘子味的冰淇淋~4 小时前
解决 vite.config.ts 引入scss 预处理报错
前端·vue·scss
小小小小宇6 小时前
V8 引擎垃圾回收机制详解
前端
lauo6 小时前
智体知识库:ai-docs对分布式智体编程语言Poplang和javascript的语法的比较(知识库问答)
开发语言·前端·javascript·分布式·机器人·开源
拉不动的猪6 小时前
设计模式之------单例模式
前端·javascript·面试
一袋米扛几楼987 小时前
【React框架】什么是 Vite?如何使用vite自动生成react的目录?
前端·react.js·前端框架
Alt.97 小时前
SpringMVC基础二(RestFul、接收数据、视图跳转)
java·开发语言·前端·mvc
进取星辰7 小时前
1、从零搭建魔法工坊:React 19 新手村生存指南
前端·react.js·前端框架
前端开发张小七8 小时前
每日一练:2.leetcode回文数
前端·python