简体   繁体   中英

How to create, listen and trigger custom event in ReactJS?

I need to create global custom event, to be able listen and trigger it. In jQuery I would do it like that:

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

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

What for?

I need to create communication between not related components.


Question:

How to listen and trigger global custom events in ReactJS ?

If you want to add listeners you can still do this with jQuery. Start listening in the componentDidMount and stop listening in componentWillUnmount see the docs . If it wants to be global (visible to child components), you can do this in the topmost component and propagate down with props.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM