React Native 页面间传值总结
各传值方式简述,总结如下:
接下来具体看看,各方式实现:
1.正向:navigator.passProps 传递props在Page A 中,传值: onClickAJumpToB(){
this.props.navigator.push({
title: 'PageB',component: ComponentName,0);">passProps: {
// 传递的props命名,看你心情(如下:bReceive)
// 传递的data类型,看你需求
bReceive: 'data - trans to B',0);">bReceive2: [object],...
}
}
);
}
在Page B中,取值: this.props.bReceive
this.props.bReceive2
2.逆向:navigator.passProps 传递func在Page A 中,取值: // ??注意:写法1。传递func,回调 - 要绑定 this,否则找不到()
xxCallback: function (arg,...) {
// 更改state,触发refresh,其中arg即为回传的值
this.setState({
key: arg,...
});
}.bind(this),// ??注意:写法2。绑定this,
// 其中newFuncForCallback为A中,另一function,如下下下...
xxCallback: this.newFuncForCallback.bind(this),161);">// ??注意:写法3。ES6,箭头函数,无需bind
xxCallback: (arg,...) => {
this.setState({
// 回调函数,写法2中的function
newFuncForCallback(){
// do somthing ...
}
在Page B中,传值: onClickBPopToA(){
if(this.props.xxCallback){
// 可传多个内容
this.props.xxCallback(arg,...);
}
}
3.注册监听(DeviceEventEmitter)// 1.在操作类中,导入DeviceEventEmitter
import {DeviceEventEmitter} from 'react-native'
// 2.注册监听
this.event = DeviceEventEmitter.addListener(eventType,(arg,...) => {
// do somthing ...
});
// 3.发出通知
DeviceEventEmitter.emit(emit: function(eventType,arg,...);
// 4.移除监听
componentWillUnMount(){
// 移除所有监听
DeviceEventEmitter.removeAllListeners();
// 移除单个监听
this.event.remove();
}
4.全局变量 global// global为系统自带,使用时无需import任何内容
// 存值
global.username = 'your name';
// 取值
global.username
额外补充:自己实现全局变量 Global = {
userName: '',161);">// 用户名
...
}
module.exports = Global;
使用Global.js: // 在使用的地方,import
import Global from 'Global.js相对当前js文件的路径'
// 存值
Global.username = // 取值
Global.username
5.持久化存储(AsynStorage/ react-native-storage)
原文链接:https://github.com/sunnylqm/react-native-storage/blob/master/README-CHN.md // 存储
global.storage.save({key:rawData:{k1:value,...}});
// 读取
global.storage.load(key:' '})
.then(ret => {
}).catch(err => {
})
// 删除
global.storage.clearMap();
6.Redux - state
有兴趣的童鞋可以仔细阅读以下: 最后
blabla:Github (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |