一、问题提出
React-Native中navigator.pop()
后如何更新前一个页面,这是一个最为常见得问题。
二、问题的描述
比如说,我们开发应用的时候,上传头像是一个最为常见的功能,我点击选择打开图库的按钮之后,push
到图库的页面,我们在上传成功后,需要pop
回到当前页面,并把图片路径传到当前页面。
三、解决办法
这个问题对于一个有Android
和ios
开发经验的程序员首先想到的就是回调函数或者广播机制等。其实在React-Native
中同样也可用回调函数来解决这个问题。
- 在A页面中实现一个声明一个函数
refresView()
- 在A页面
push
参数中增加一个回掉函数callBack(msg)
- 在B页面
pop
时候调用callBack
将值传回,更新界面
四、代码的实现
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);
B页面的实现
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
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;
参考:
https://blog.csdn.net/u010046908/article/details/52453794
网友评论