给大家介绍一个实用的RN神器DeviceEventEmitter

时间:2023-03-09 16:42:42
给大家介绍一个实用的RN神器DeviceEventEmitter

再不出来更新一下自己都感觉不到自己还存在了,这个监听最常用的地方莫过于单选和全选了,,当然远不止这个了,大家可以自己去多尝试几波,举个栗子

A组件全选所在

//全选

choose(bool){
//选中
if(bool){
DeviceEventEmitter.emit('allChoose’);
}else{
//全不选
DeviceEventEmitter.emit('allNoChoose’); }

B组件单选所在地

componentDidMount(){
//监第二个参数是函数,
this.subscription =DeviceEventEmitter.addListener('allChoose’,this.chooseSomething.bind(this));
};
chooseSomething(){
//这里就可以做一些事情啦
}
//不用了记得移除
componentWillUnmount(){
this.subscription.remove();
};

就是这么粗暴,不用传来传去,当然头部还是要引入这个文件的 import {DeviceEventEmitter} from 'react-native';