事件发送器和用户ES6语法与反应本地
问题描述:
我想实现事件发送器/订阅者关系在两个组件之间的反应原生类。我见过参考下列材料:事件发送器和用户ES6语法与反应本地
- React Native - Event Emitters by Colin Ramsay
- React Native - Call Function of child from NavigatorIOS
这些解决方案是足够的什么,我试图完成,然而,他们懒得需要接收组件上使用的mixins: [Subscribable.Mixin]
与Subscriber
正常工作。不幸的是,我使用ES6并从Component
扩展我的类,所以我不能使用这个mixin语法。
我的问题是:如何在不使用mixin的情况下在ES6中实现上述解决方案?
答
。
简单的演示:
import EventEmitter from 'EventEmitter';
let x = new EventEmitter();
function handler(arg) {
console.log(`event-name has occurred! here is the event data arg=${JSON.stringify(arg)}`);
}
x.addListener('event-name', handler);
x.emit('event-name', { es6rules: true, mixinsAreLame: true });
为addListener
完整签名需要三个参数:
EventEmitter.addListener(eventName, handler, handlerContext)
在反应组件,您可能希望使用此背景下阿根廷,从而使处理器可以类方法,而不是内联函数,仍然保留this == component instance
。例如: -
componentDidMount() {
someEmitter.addListener('awesome', this.handleAwesomeEvents, this);
// the generalist suggests the alternative:
someEmitter.addListener('awesome', this.handleAwesomeEvents.bind(this));
}
handleAwesomeEvents = (event) => {
let awesomeness = event.awesomeRating;
// if you don't provide context in didMount,
// "this" will not refer to the component,
// and this next line will throw
this.setState({ awesomeness });
};
FYI:我从看决然unmagical实施the infamous Subscribable mixin得到这个。 Google的搜索结果基本上是Ramsay单个混音演示的回声室。
P.S.至于将这个发射器暴露给另一个器件,我可能会拥有拥有的器件提供用于接收发射器参考的功能,并且创建发射器的组件将随后有条件地用发射器执行该道具。
// owner's render method:
<ThingThatEmits
onEmitterReady={(emitter) => this.thingEmitter = emitter}
/>
// inside ThingThatEmits:
componentDidMount() {
this.emitter = new EventEmitter();
if(typeof this.props.onEmitterReady === 'function') {
this.props.onEmitterReady(this.emitter);
}
}
答
我能用react-mixin得到解决方法。不知道它有多适当,但它没有任何修改。关键是在类定义之后添加reactMixin(DetailView.prototype, Subscribable.Mixin);
。
去关闭该浮动周围EventEmitter和可订阅的例子:你不需要混入使用EventEmitters
'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);
这里有人建议使用简单地使用写组件的“老办法”:http://hi-tips.tumblr.com/post/137014836571/use-eventemitter-for-calling-child-component -event 我有同样的问题,并想知道是否有任何适当的方式在ES6中做这个 –
我仍然在寻找这个。我不愿意开始使用'react-mixin'。 – Tom