ReactNative页面跳转Navigator实现的示例代码(3)

如果当我们返回的时候需要携带参数,我们可以通过给navigator设置一个回调方法,用于给第一个页面设置信息,这样就可以完成返回时数据的传递了。

完整代码如下所示:

index.android.js

'use strict'; import React, { AppRegistry, Component, StyleSheet, Text, Image, TextInput, View, Navigator } from 'react-native'; import FirstPageComponent from './app/src/FirstPageComponent'; export default class MyProject extends React.Component { render() { var defaultName = 'FirstPageComponent'; var defaultComponent = FirstPageComponent; return ( <Navigator //指定了默认的页面,也就是启动app之后会看到的第一屏,需要两个参数,name跟component initialRoute={{ name: defaultName, component: defaultComponent }} configureScene={(route) => { //跳转的动画 return Navigator.SceneConfigs.FadeAndroid; }} renderScene={(route, navigator) => { let Component = route.component; if(route.component){ return <Component {...route.params} navigator={navigator} /> } }} /> ); } } AppRegistry.registerComponent('MyProject', () => MyProject);

FirstPageComponent.js

import React,{ View, Text, TouchableOpacity } from 'react-native'; import SecondPageComonent from "./SecondPageComponent"; export default class FirstPageComponent extends React.Component{ constructor(props){ super(props); this.state = { resultMessage:"hello", }; } _pressButtoon(){ var _this = this; const { navigator} = this.props; if (navigator) { navigator.push({ name:'SecondPageComonent', component:SecondPageComonent, params:{ message:"I am from FirstPageComponent", getResult:function(myMessage){ _this.setState({ resultMessage:myMessage, }) } } }) } } render(){ return ( <View> <TouchableOpacity onPress={this._pressButtoon.bind(this)}> <Text>{this.state.resultMessage}</Text> </TouchableOpacity> </View> ); } }

SecondPageComponent.js

import React,{ View, Text, TouchableOpacity, } from 'react-native'; import FirstPageComponent from './FirstPageComponent'; export default class SecondPageComponent extends React.Component{ constructor(props){ super(props); this.state = { message:"", }; } componentDidMount(){ this.setState({ message:this.props.message, }); } _pressButton(){ const { navigator } = this.props; if(this.props.getResult){ this.props.getResult("This is from SecondPageComponent"); } if(navigator){ navigator.pop(); } } render(){ return ( <View> <TouchableOpacity onPress={this._pressButton.bind(this)}> <Text>{this.state.message}</Text> </TouchableOpacity> </View> ); } }

最终效果如下所示:

ReactNative页面跳转Navigator实现的示例代码

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wyjyww.html