1.首先利用导航做一个由首页跳转到详情页效果,在首页引入DeviceEventEmitter通知组件,然后在首页的componentDidMount方法注册一个通知,想要接收发送者发了的通知必须先注册通知。 实现代码如下,在首页注册通知
import {
AppRegistry,
StyleSheet,
Text,
View,
ListView,
TouchableOpacity,
DeviceEventEmitter,//引入监听事件
} from 'react-native';
import {Navigator} from 'react-native-deprecated-custom-components';
import Detail from './Detail';
export default class SectionDemo extends Component {
render() {
let defauleName='Main';
let defauleComponent=Main;
return (
<Navigator initialRoute={{name:defauleName,component:defauleComponent}}
configureScene={(route) =>{
var conf = Navigator.SceneConfigs.PushFromRight;
// 禁止滑动返沪上一页
conf.gestures = null;
return conf;
}}
renderScene={(route,navigator) =>{
let Component = route.component;
return <Component {...route.params} navigator={navigator}/>
}}
/>
);
}
}
class Main extends Component{
constructor(props) {
super(props);
//初始按钮的颜色和文字
this.state = {
color:'orange',
text:'进到详情页'
};
}
//注册通知
componentDidMount(){
DeviceEventEmitter.addListener('ChangeUI',(dic)=>{
//接收到详情页发送的通知,刷新首页的数据,改变按钮颜色和文字,刷新UI
this.setState({
text:dic.text,
color:dic.color
});
});
}
//页面跳转
detail(){
// alert(name);
this.props.navigator.push({
component:Detail,
params:{
},
});
}
render() {
return (
<View style={styles.container}>
<TouchableOpacity style={{height:40,
width:100,
backgroundColor:this.state.color,
justifyContent:'center',
alignItems:'center'}}
onPress={()=>{this.detail()}}>
<Text>{this.state.text}</Text>
</TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#F5FCFF',
alignItems: 'center',
justifyContent: 'center',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('SectionDemo', () => SectionDemo);
2.看一下详情页,详情页也是要引入DeviceEventEmitter通知组件利用React Native的生命周期方法,在页面将要离开的时候发送一个通知方法给首页,这样首页接收到通知,就会执行刷新页面的操作了。代码实现如下
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
TouchableOpacity,
DeviceEventEmitter
} from 'react-native';
export default class Detail extends Component {
//页面将要离开的是时候发送通知
componentWillUnmount(){
DeviceEventEmitter.emit('ChangeUI', {color:'red',text:'通知'});
}
//返回首页
back=()=>{
this.props.navigator.pop();
}
render() {
return (
<View style={styles.container}>
<TouchableOpacity style={{width:100,height:40,backgroundColor:'red'}}
onPress={()=>{this.back()}}>
<Text>返回</Text>
</TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
});
实现效果如图,返回的时候首页的按钮和文字改变了
QQ20170811-091115-HD.gif