1.首先利用導航做一個由首頁跳轉(zhuǎn)到詳情頁效果,在首頁引入DeviceEventEmitter通知組件叽奥,然后在首頁的componentDidMount方法注冊一個通知,想要接收發(fā)送者發(fā)了的通知必須先注冊通知蔬螟。 實現(xiàn)代碼如下,在首頁注冊通知
import {
AppRegistry,
StyleSheet,
Text,
View,
ListView,
TouchableOpacity,
DeviceEventEmitter,//引入監(jiān)聽事件
} 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)=>{
//接收到詳情頁發(fā)送的通知,刷新首頁的數(shù)據(jù)盗蟆,改變按鈕顏色和文字,刷新UI
this.setState({
text:dic.text,
color:dic.color
});
});
}
//頁面跳轉(zhuǎn)
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的生命周期方法喳资,在頁面將要離開的時候發(fā)送一個通知方法給首頁,這樣首頁接收到通知腾供,就會執(zhí)行刷新頁面的操作了仆邓。代碼實現(xiàn)如下
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
TouchableOpacity,
DeviceEventEmitter
} from 'react-native';
export default class Detail extends Component {
//頁面將要離開的是時候發(fā)送通知
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',
},
});
實現(xiàn)效果如圖,返回的時候首頁的按鈕和文字改變了