react-native,下一级页面如何向上一级页面传递参数
需求背景:
从页面A跳转到月面B,当B中选择或者输入数据后,需要更新A的页面,并且返回到A页面。
有两种解决方法:
1、在A跳转到B的时候,传入回调函数作为参数:
A页面中代码:
NavigationManager.jump(this,PageName.B页面,{'keyword':this.state.keyword,'refresh':(bparam)=>{
console.log('打印B页面传过来的参数:',bparam);
}})
这里跳转到B页面的时候,给B页面传入了一个参数refresh,这个refresh是个回调函数(接收一个参数bparam);
B页面中代码:
let params = NavigationManager.getParams(this);
param.refresh('我是B页面的参数');
这个时候可以看到,控制台打印出了:打印B页面传过来的参数: 我是B页面的参数。
通过上述过程,我们已经把B页面的参数传递给了上一级A页面,并且执行了A中的更新。
2、利用DeviceEventEmitter由B页面向A页面发通知
A页面中代码:
import { DeviceEventEmitter}from 'react-native';
componentWillMount(){
this.schemeSearchListner =DeviceEventEmitter.addListener(EventType.'你的消息名字,自定义', (data) => {
this.setState({'keyword':data});
//做你收到消息后想做的事情
});
}
//记得移除
componentWillUnmount(){
this.schemeSearchListner &&this.schemeSearchListner.remove();
}
B页面中代码:
//发送消息
DeviceEventEmitter.emit(EventType.'自定义的通知消息', this.state.content);
其中this.state.content是你要向A传递的参数,可以自由定义,这样就完成从B到上一级页面的参数传递。