react native的事件通知 DeviceEventEmitter
    		       		warning:
    		            这篇文章距离上次修改已过445天,其中的内容可能已经有所变动。
    		        
        		                
                React Native 提供了一个用于跨组件通信的模块,即 DeviceEventEmitter。它可以在任何组件中发送事件,并在任何组件中接收这些事件。
解决方案1:
在一个组件中发送事件:
import { DeviceEventEmitter } from 'react-native';
 
// 发送事件
DeviceEventEmitter.emit('eventName', arg1, arg2, ...);在另一个组件中接收事件:
import { DeviceEventEmitter } from 'react-native';
 
// 监听事件
componentDidMount() {
  this.eventEmitter = DeviceEventEmitter.addListener('eventName', this.handleEvent);
}
 
// 移除监听
componentWillUnmount() {
  this.eventEmitter.removeListener();
}
 
// 事件处理函数
handleEvent(arg1, arg2, ...) {
  // 处理事件
}解决方案2:
使用回调函数来接收事件。
import { DeviceEventEmitter } from 'react-native';
 
// 发送事件
DeviceEventEmitter.emit('eventName', arg1, arg2, ...);
 
// 接收事件
componentDidMount() {
  DeviceEventEmitter.addListener('eventName', this.handleEvent);
}
 
// 移除监听
componentWillUnmount() {
  DeviceEventEmitter.removeAllListeners('eventName');
}
 
// 事件处理函数
handleEvent(arg1, arg2, ...) {
  // 处理事件
}注意:
- 使用 DeviceEventEmitter 时,需要在组件的 componentDidMount 方法中添加监听器,并在 componentWillUnmount 方法中移除监听器。
 - 如果不移除监听器,可能会导致内存泄漏。
 - 如果你的事件只需要被触发一次,可以使用 emit 方法发送事件,并在其他组件中使用 addListener 方法来监听并接收这个事件。
 - 如果你希望一个函数在事件触发时被多次调用,可以使用 addListener 方法来注册一个监听器,并在不需要监听事件时使用 removeListener 方法来移除监听器。
 
评论已关闭