1、问题提出
React-Native中navigator.pop()后如何更新前一个页面,这是一个最为常见得问题。
2、问题的描述
比如说,我们开发应用的时候,上传头像是一个最为常见的功能,我点击选择打开图库的按钮之后,push到图库的页面,我们在上传成功后,需要pop回到当前页面,并把图片路径传到当前页面。
3、React-Native中的解决办法
这个问题对于一个有Android和ios开发经验的程序员首先想到的就是回调函数或者广播机制等。其实在React-Native中同样也可用回调函数来解决这个问题。本来想以android来举例实现,最后还是算了直接上React-Native吧。
4.代码的实现
4.A页面的实现
/**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React,{ Component } from 'react';
import {
AppRegistry,StyleSheet,Text,Navigator,ToastAndroid,View
} from 'react-native';
import Button from './Button';
import Test from './test';
var _navigator;
var d;
class Hello2 extends Component {
constructor(props){
super(props);
d = this;
this.state = {city:''}
// this.refeshView = this.refeshView.bind(this);
}
configureScene(route){
return Navigator.SceneConfigs.FadeAndroid;
}
refeshView(msg){
console.log('刷新');
d.setState({'city':msg});
console.log('end');
}
renderScene(router,navigator){
console.log(d);
_navigator = navigator;
if(router.id === 'main'){
return <View style={styles.container}>
<Button onPress={() => {
console.log('start');
_navigator.push({title:'MainPage',id:'page',callBack:(msg)=>{ console.log(d); d.refeshView(msg); console.log('end');}}); }} text={'打开'} style={styles.instructions} disabled = {false}/> <Text style={styles.welcome}> {d.state.city} </Text> <Text style={styles.instructions}> </Text> <Text style={styles.instructions}> Press Cmd+R to reload,{'\n'} Cmd+D or shake for dev menu </Text> </View> }else if(router.id === 'page'){ return ( <Test navigator={navigator} router={router}/> ); } } render() { return ( <Navigator initialRoute={{ title: 'Main',id:'main'}} configureScene={this.configureScene} renderScene={this.renderScene} /> ); } } const styles = StyleSheet.create({ container: { flex: 1,justifyContent: 'center',alignItems: 'center',backgroundColor: '#F5FCFF',},welcome: { fontSize: 20,textAlign: 'center',margin: 10,instructions: { textAlign: 'center',color: '#333333',marginBottom: 5,}); AppRegistry.registerComponent('Hello2',() => Hello2);
4.2、B页面的实现
import React,{ Component } from 'react';
import {
AppRegistry,View
} from 'react-native';
var _navigator;
import Button from './Button';
class Test extends Component {
render() {
return (
<View style={{flex:1}}>
<Button onPress={() => {
console.log(this.props);
this.props.router.callBack('I am a Student');
this.props.navigator.pop();
}} text={'返回'} style={styles.instructions} disabled = {false}/>
</View>
);
}
}
const styles = StyleSheet.create({
instructions: {
textAlign: 'center',color: '#126798',marginTop: 50,}
});
module.exports = Test;
代码非常的简单,谢谢大家学习。