【问题标题】:How to create, listen and trigger custom event in ReactJS?如何在 ReactJS 中创建、监听和触发自定义事件?
【发布时间】:2016-07-13 14:57:50
【问题描述】:

我需要创建全局自定义事件,以便能够监听和触发它。 在 jQuery 我会这样做:

$(document).on('myCustomEvent', function(){
    console.log("myCustomEvent triggered");
})

$(document).trigger('myCustomEvent');

为了什么?

我需要在不相关的组件之间创建通信。


问题:

如何在ReactJS监听触发全局自定义事件

【问题讨论】:

    标签: javascript reactjs events event-handling jquery-events


    【解决方案1】:

    如果你想添加监听器,你仍然可以使用 jQuery 来完成。开始收听componentDidMount 并停止收听componentWillUnmount 请参阅the docs。如果它想要是全局的(对子组件可见),您可以在最顶层的组件中执行此操作并使用 props 向下传播。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-06
      • 2011-10-19
      • 2011-10-19
      相关资源
      最近更新 更多