react-native - EventEmitter 和 Subscriber ES6 语法与 React Native

标签 react-native mixins eventemitter

我正在尝试在 React Native 类中实现两个组件之间的 EventEmitter/Subscriber 关系。我看到引用了以下 Material :

这些解决方案足以满足我想要完成的任务,但是,它们需要在接收组件上使用 mixins: [Subscribable.Mixin] 才能与 Subscriber< 正常工作。不幸的是,我正在使用 ES6 并从 Component 扩展我的类,因此我无法使用此 mixin 语法。

我的问题是:如何在不使用 mixins 的情况下在 ES6 中实现上述解决方案?

最佳答案

您不需要 mixins 即可使用 EventEmitters。

简单演示:

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)

在 React 组件中,您可能希望使用该上下文参数,以便处理程序可以是类方法而不是内联函数,并且仍然保留 this == 组件实例。例如:

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 });
};

仅供引用:我通过查看 the infamous Subscribable mixin 的绝对不神奇的实现得到了这一点。 。 Google 搜索结果基本上是 Ramsay 的基于 mixin 的单一演示的回声室。

附注至于将此发射器暴露给另一个组件,我可能会让拥有的组件提供一个用于接收发射器引用的函数,然后创建发射器的组件将有条件地使用发射器执行该 Prop 。

// 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-native - EventEmitter 和 Subscriber ES6 语法与 React Native,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36774540/

相关文章:

javascript - 在 react native 的android真实设备上运行应用程序时console.log输出在哪里

javascript - 根据导航状态更改导航栏

Angular 2 : emitter listener between components

c++ - 我应该更喜欢 mixin 还是函数模板来为一组不相关的类型添加行为?

javascript - Angular 服务中的 EventEmitter 是好是坏?

node.js - 警告 : occur node apn emitter. setMaxListeners()

android - Netinfo.isConnected.fetch() 返回真

javascript - 可能未处理的 promise 拒绝(id :0): undefined is not an object

css - 使用 LESS CSS 的 CSS 关键帧中的 @ 符号和变量

language-agnostic - 目前支持 mixins 的语言有哪些?