react-native页面之间的相互传值
之前在自己学习react-native的时候,在页面跳转和传值问题上花了一段时间去网上搜索和查找资料,自己总结了两个方法。可以参考 https://blog.csdn.net/shb2058/article/details/80390468 和 https://blog.csdn.net/shb2058/article/details/80432014
首先设置一个不带参数的页面跳转使用navigation
切换路由方法:
- this.props.navigation.goBack() 返回上一层
- this.props.navigation.popToTop() 返回堆栈最顶层
- this.props.navigation.push(‘Details’) 继续往下推送新的路由,相当于子页面的子页面
- this.props.navigation.navigate(‘Details’) 将新路由推送到导航器中,如果没有在导航器中,则跳转到该页面
父页面:
import {Component} from "react"; import { Text,AlertStatic as Alert, TouchableOpacity, View, DeviceEventEmitter } from "react-native"; import {createStackNavigator} from "react-navigation"; import B from '../B.js'; calss A extends Component { render(){ return( <View> <TouchableOpacity onpress={ ()=>{ this.props.navigation.navigate('B') } }> <Text>点击跳转</Text> </TouchableOpacity> </View> ) } } const HomeScreen = createStackNavigator({ Home: {screen: A}, Details: {screen: B}, }); module.exports = A;
子页面:
import {Component} from "react"; import { Text, TouchableOpacity, View, DeviceEventEmitter } from "react-native"; class B extends Component { render(){ return( <View> <TouchableOpacity onpress={ ()=>{ this.props.navigation.goBack(); } }> <Text>点击返回</Text> </TouchableOpacity> </View> ) } } module.exports = B;
接下来带参数传递
父页面传给子页面
<TouchableOpacity onpress={ ()=>{ this.props.navigation.navigate('B',{ params:xx, }) } }>
子页面接收参数
constructor(props){ super(props); const {navigation} = this.props; let yy = navigation.getParam("params"); }
这样子页面就获取到父页面传递过来的值了。
然后是子页面带参数返回页面
方法一:
子页面传递参数
<TouchableOpacity onpress={ ()=>{ this.props.navigation.state.params.callBack(params); this.props.navigation.goBack(); } }> <Text>点击返回</Text> </TouchableOpacity>
父页面接收参数
<TouchableOpacity onpress={ ()=>{ this.props.navigation.navigate('B',{ params:xx, callBack:(params) =>{ Alert(params); } }) } }>
方法二:添加一个监听器DeviceEventEmitter
子页面
TouchableOpacity onpress={ ()=>{ DeviceEventEmitter.emit('returnData',params); this.props.navigation.goBack(); } }> <Text>点击返回</Text>
父页面
componentDidMount() { DeviceEventEmitter.addListener("returnData", (params) => { Alert(params); }) }
OK,就这样了~~~