EventEmitter and Subscriber ES6 Syntax with React Native

前端 未结 3 2012
青春惊慌失措
青春惊慌失措 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:25

    I was able to get a workaround with react-mixin. Not sure how proper it is, but it works without any modification. The key is adding reactMixin(DetailView.prototype, Subscribable.Mixin); after the class definition.

    Going off the example that is floating around for EventEmitter and Subscribable:

    'use strict';
    
    var reactMixin = require('react-mixin');
    var React = require('react-native');
    var EventEmitter = require('EventEmitter');
    var Subscribable = require('Subscribable');
    
    var {
        AppRegistry,
        StyleSheet,
        Text,
        View,
        NavigatorIOS
    } = React;
    
    class MainView extends Component {
        constructor(props){
          super(props);
          this.EventEmitter = new EventEmitter();
        }
    
        somethingHappenedFunction(){
          this.EventEmitter.emit("update_event", { message: "hello from up here"});
        }
    
        //rest of the class
    }
    
    class DetailView extends Component {
       componentDidMount(){
         this.addListenerOn(this.props.events, 'update_event', this.miscFunction);
       }
    
       miscFunction(args) {
        console.log("message: %s", args.message);
       }
    
       //rest of the class
    }
    reactMixin(DetailView.prototype, Subscribable.Mixin);
    

提交回复
热议问题