EventEmitter and Subscriber ES6 Syntax with React Native

前端 未结 3 1998
青春惊慌失措
青春惊慌失措 2020-12-25 14:13

I am trying to implement an EventEmitter/Subscriber relationship between two components in a react native class. I have seen referenced the following materials:

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-25 14:29

    This might be a very late answer, but I'm just going to put it out there for anyone who might find this useful.

    As of the time of writing this answer (July, 2020), React Native has changed a lot since version 0.60.0+, you can either use an instance of EventEmitter, or statically call the DeviceEventEmitter methods.


    Here is an example using EventEmitter:

    
    import { EventEmitter } from 'events';
    
    const newEvent = new EventEmitter();
    
    // then you can use: "emit", "on", "once", and "off"
    newEvent.on('example.event', () => {
      // ...
    });
    
    

    Another example using the DeviceEventEmitter:

    
    import { DeviceEventEmitter } from 'react-native';
    
    // then you can directly use: "emit", "addListener", and "removeAllListeners"
    DeviceEventEmitter.emit('example.event', ['foo', 'bar', 'baz']);
    
    

    Hope that comes handy for anyone who still looking for a way to implement custom events in React Native.

提交回复
热议问题