我试图在react-native 类的两个组件之间实现EventEmitter/Subscriber关系.我看过以下material :

这些解决方案对于我试图实现的目标来说已经足够了,但是,它们需要在接收组件上使用mixins: [Subscribable.Mixin]才能与Subscriber正常工作.不幸的是,我正在使用ES6并从Component扩展我的类,所以我不能使用这种混合语法.

我的问题是:如果不使用mixin,如何在ES6中实现上述解决方案?

推荐答案

使用EventEmitter不需要mixin.

简单演示:

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

仅供参考:我之所以这么做,是因为我看到the infamous Subscribable mixin的实现毫无逻辑可言.谷歌的搜索结果基本上是拉姆齐基于mixin的单一演示的回声室.

另外,就将这个emits 器expose 给另一个组件而言,我可能会让拥有它的组件提供一个接收emits 器引用的函数,然后创建emits 器的组件将有条件地使用emits 器执行该props .

// 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相关问答推荐

如何在renderItem中显示每个项目的索引号,保持分页的前一个下一个按钮

FlatList有时不会在数据更改时重新呈现

如何根据设备主题更改React Native中状态栏的背景?

元素类型无效:应为字符串

在 ReactNative 中调用 RCTDeviceEventEmitter.emit 时出错

react-native 自定义视图,原生 prop 没有 propType

在向后滑动时执行操作(react-navigation )

React Native React 导航标题按钮事件

在Windows中连接到远程调试器时react-native 超时

子视图覆盖的容器borderRadius,这是一个bug吗?

React Native 中如何使用 Flex 居中组件?

试图注册两个同名的视图 RNGestureHandlerButton

React Navigation TabNavigator:在选项卡更改时重置上一个选项卡

react-native Http 拦截器

如何在 Text 中围绕 Text 包裹 TouchableOpacity?

Firebase 3.3 实时数据库坚持使用 React Native 0.32 Making a connection attempt

React Native 动画 - zoom 时 translateX 和 translateY

区别需要MainQueueSetup 和dispatch_get_main_queue?

在 React-Native 中手动设置 opacity 的 onPress of TouchableOpacity 的音量

Android 是否支持 React Native 的 LayoutAnimation?