【React Native】DeviceEventEmitter监听通知及带参数传值

  1、基本语法

  (1)接收通知格式

import { DeviceEventEmitter } from 'react-native';
...
componentDidMount() {
    //收到监听
    this.listener = DeviceEventEmitter.addListener('通知名称', (message) => {
    //收到监听后想做的事情
    console.log(message);  //监听
    })
}
componentWillUnmount() {
    //移除监听
    if (this.listener) {
      this.listener.remove();
    }
  }

  (2)发送通知格式

//发送通知 第一个参数是通知名称,后面的参数是发送的值可以多个
    DeviceEventEmitter.emit('通知名称','message',...)

  使用实例:

  在接收方...

componentDidMount(): void {

    this.subscription = DeviceEventEmitter.addListener('createOops',()=> {
  
    });
  }

componentWillUnmount(): void {
    this.subscription.remove()
  }

  在发送方...

DeviceEventEmitter.emit('createOops')
原文地址:https://www.cnblogs.com/xjf125/p/12285409.html