react native 之 事件監聽 和 回調函數


同原生一樣,react native 同樣也有事件監聽和回調函數這玩意.

場景很多,比如:A界面push到B界面,B界面再pop回A界面,可以給A界面傳值或者告訴A刷新界面.

事件監聽

事件監聽類似於iOS原生的通知,一個發,一個收即可.

A界面收:

1 import {
2     DeviceEventEmitter
3 } from 'react-native';
 1  componentDidMount() {
 2         //收到監聽
 3         this.listener = DeviceEventEmitter.addListener('通知名稱',(e)=>{
 4             alert(e)
 5         });
 6     }
 7     componentWillUnmount(){
 8         // 移除監聽 
 9         this.listener.remove();
10     }

B界面在pop回A界面的時候發:

1 import {
2     DeviceEventEmitter
3 } from 'react-native';
1     pop = ()=>{
2         let value = '監聽'   //准備一個值
3         DeviceEventEmitter.emit('通知名稱',value); //發監聽
4         this.props.navigator.pop({ })
5     }

事件回調 

A界面在push到B界面的時候定義個回調函數

1 push = () =>{
2     this.props.navigator.push({
3         component:DetailsView,
4         passProps:{
5             callback:(msg)=>{ alert(msg) }
6         }
7     })
8 }

 

B界面在pop回A界面的時候調用該回調函數

1 pop = () =>{
2 
3     this.props.navigator.pop({
4     })
5 
6     if(this.props.callback){
7         this.props.callback('回調')
8     }
9 }

 

大致效果:

 

                                                                                                                             

 

github: https://github.com/pheromone/react_native_callback_emitter 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM