1. 利用react-native 事件DeviceEventEmitter 監(jiān)聽廣播
應(yīng)用場景:
	- 表單提交頁面, A頁面跳轉(zhuǎn)到B頁面選人, 然后返回A頁面, 需要將B頁面選擇的數(shù)據(jù)傳回A頁面。
	- 多個多媒體來回切換播放,暫停后二次繼續(xù)播放等問題。
代碼如下:
A頁面
 componentDidMount() { // 利用DeviceEventEmitter 監(jiān)聽 concactAdd事件  this.subscription = DeviceEventEmitter.addListener('concactAdd', (dic) => {// dic 為觸發(fā)事件回傳回來的數(shù)據(jù)   // 接收到 update 頁發(fā)送的通知,后進行的操作內(nèi)容   if (dic.approver_list) {    this.setState((preState: Object) => {     this.updateInputValue(preState.approver_list.concat(dic.approver_list), 'approver_list');     return { approver_list: preState.approver_list.concat(dic.approver_list) };    });   }   if (dic.observer_list) {    this.setState((preState: Object) => {     this.updateInputValue(preState.observer_list.concat(dic.observer_list), 'observer_list');     return { observer_list: preState.observer_list.concat(dic.observer_list) };    });   }  });...componentWillUnmount() {  this.subscription.remove();}B頁面
// 觸發(fā)concactAdd事件廣播handleOk = (names: []) => {  const { field } = this.props;  DeviceEventEmitter.emit('concactAdd', { [field]: names }); }2. 用react-navigation提供的路由之間
A頁面
// 定義路由跳轉(zhuǎn)函數(shù) cb表示需要傳遞的回調(diào)函數(shù)export const navigateToLinkman = (cb: Function, type?: string, mul?: boolean): NavigateAction => NavigationActions.navigate({ routeName: 'Linkman', params: { cb, type, mul } }); // 跳轉(zhuǎn)選擇人員頁面  handleSelectUser = () => {   Keyboard.dismiss();   this.props.actions.navigateToLinkman(this.selectedUser, '', true);...// 選擇人員后的回調(diào)函數(shù)selectedUser = (selectUser: string[]) => {   this.setState((preState) => {    const newEmails = preState.emails.concat(selectUser);    const emails = [...new Set(newEmails)];    return {     emails,    };   });  }B頁面
handleToUser = () => {  ...  navigation.state.params.cb(user.email, group);  ...}3. 利用react-navigation 提供的路由事件監(jiān)聽觸發(fā)事件
在A頁面路由失去焦點的時候觸發(fā)該事件
componentDidMount() { this.props.navigation.addListener('didBlur', (payload) => {     if (this.modalView) this.modalView.close();    });  }那么問題來了, 為何不在頁面卸載(componentWillunmount)的時候觸發(fā)該事件?
如果不了解react-native和react-navigation, 會很困惑, A頁面卸載了, 為什么還能接收到來自B頁面的數(shù)據(jù)或者事件, 原因是: react-navigation中, A頁面跳轉(zhuǎn)到B頁面, A頁面沒有卸載, 只是在它提供的路由棧中堆積,例如A跳轉(zhuǎn)到B中, A頁面不執(zhí)行componentWillunmount,當(dāng)每一個路由pop掉的時候才會執(zhí)行componentWillunmount, 卸載掉當(dāng)前頁面。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持VeVb武林網(wǎng)。
新聞熱點
疑難解答