React 中独立组件间如何通信

发布日期:2026-07-16 02:48:03   来源 : 杭州电子商务研究院    浏览量 :10
杭州电子商务研究院 发布日期:2026-07-16 02:48:03  
10

介绍

React 最棒的功能之一是它可以帮助您构建组件化应用。您可以构建较小的组件,每个组件都有自己的职责,然后将它们组合起来以创建完整的应用。这些组件通常需要相互通信以在应用中传递数据。

React 使用 props 在依赖组件之间进行通信。不过,有时您可能希望在两个没有共同数据共享功能的独立组件之间进行通信。在本指南中,您将学习如何使用事件总线在独立组件之间进行通信。

创建事件总线

要在 React 中实现两个独立组件之间的通信,您可以灵活地设置全局事件驱动系统或PubSub系统。事件总线实现了 PubSub 模式,并允许您监听和分派来自组件的事件。事件总线可帮助您解耦组件并使用从其他组件触发的事件传递数据,这样它们之间就不会有直接依赖关系。

事件总线有三种方法:ondispatchremove

      const eventBus = {
  on(event, callback) {
    // ...
  },
  dispatch(event, data) {
    // ...
  },
  remove(event, callback) {
    // ...
  },
};
    

on()方法中,将事件侦听器附加到文档对象。on方法将有两个参数:事件和回调函数。 事件触发时将调用回调函数。

      // ...
on(event, callback) {
    document.addEventListener(event, (e) => callback(e.detail));
},
// ...
    

dispatch ()方法将使用CustomEvent API 以及一些数据触发事件。

      // ...
dispatch(event, data) {
    document.dispatchEvent(new CustomEvent(event, { detail: data }));
},
// ...
    

最后,remove()方法将从文档对象中删除附加事件,以防止应用程序中的内存泄漏。

      // ...
remove(event, callback) {
    document.removeEventListener(event, callback);
},
// ...
    

使用事件总线

用于通信

现在您已经创建了自定义事件总线,现在是时候使用它在组件之间传递数据了。

假设您有两个组件:一个Coupon组件和一个Message组件。Coupon组件有一个文本字段和一个提交按钮。单击提交按钮时,该组件会触发couponApply事件以及自定义消息。Message组件监听couponApply事件并显示事件中传递的消息。

      // Coupon Component

import eventBus from "./EventBus";

class Coupon extends Component {
  constructor(props) {
    super(props);
    this.state = {
      couponCode: "",
    };
  }

  applyCoupon = () => {
    console.log("applying");
    eventBus.dispatch("couponApply", { message: "coupone applied" });
  };

  render() {
    return (
      <div>
        <input
          value={this.state.couponCode}
          onChange={(e) => this.setState({ couponCode: e.target.value })}
        />
        <button onClick={this.applyCoupon}>Apply Coupon</button>
      </div>
    );
  }
}
    

Message组件中,监听componentDidMount()生命周期方法中的事件,并在组件的componentWillUnmount()方法中使用remove()方法。当组件从 DOM 中卸载时,React 将清理事件监听器并避免内存泄漏,这可能会导致应用程序出现性能问题。

      // Message Component

import eventBus from "./EventBus";

class Message extends Component {
  constructor(props) {
    super(props);
    this.state = {
      message: "",
    };
  }

  componentDidMount() {
    eventBus.on("couponApply", (data) =>
      this.setState({ message: data.message })
    );
  }

  componentWillUnmount() {
    eventBus.remove("couponApply");
  }

  render() {
    return <div>{this.state.message}</div>;
  }
}
    

完整代码

您可以在本节中查看整个代码以供参考。

EventBus.js

      const eventBus = {
  on(event, callback) {
    document.addEventListener(event, (e) => callback(e.detail));
  },
  dispatch(event, data) {
    document.dispatchEvent(new CustomEvent(event, { detail: data }));
  },
  remove(event, callback) {
    document.removeEventListener(event, callback);
  },
};

export default eventBus;
    

Coupon.js

      import React, { Component } from "react";

import eventBus from "./EventBus";

class Coupon extends Component {
  constructor(props) {
    super(props);
    this.state = {
      couponCode: "",
    };
  }

  applyCoupon = () => {
    console.log("applying");
    eventBus.dispatch("couponApply", { message: "coupone applied" });
  };

  render() {
    return (
      <div>
        <input
          value={this.state.couponCode}
          onChange={(e) => this.setState({ couponCode: e.target.value })}
        />
        <button onClick={this.applyCoupon}>Apply Coupon</button>
      </div>
    );
  }
}

export default Coupon;
    

消息.js

      import React, { Component } from "react";
import eventBus from "./EventBus";

class Message extends Component {
  constructor(props) {
    super(props);
    this.state = {
      message: "",
    };
  }

  componentDidMount() {
    eventBus.on("couponApply", (data) =>
      this.setState({ message: data.message })
    );
  }

  componentWillUnmount() {
    eventBus.remove("couponApply");
  }

  render() {
    return <div>{this.state.message}</div>;
  }
}

export default Message;
    

结论

使用事件总线在 React 组件之间进行通信并不常见,但在解耦或独立组件之间的通信方面非常有用。在开发大型应用程序时,您不会想使用自定义事件总线,而是依赖其他库,如PubSub.jsRedux。Context API 也可用于在组件之间传递数据,但这需要额外的包装器组件,这可能会使组件难以维护。

以上内容来自杭州电子商务研究院推送
关注
关于我们
热门推荐
合作伙伴
免责声明:本站部分资讯来源于网络,如有侵权请及时联系客服,我们将尽快处理
Copyright © 2025-2027 ToB产业网址导航 公安备案 浙公网安备33010602013138号 浙ICP备16025413号-9
支持 反馈 关注 数据