React-Native學習筆記之:導航器Navigator實現頁面間跳轉
阿新 • • 發佈:2019-01-05
Navigator用來實現不同頁面的切換,想設定Navigator,必須確定一個或多個呼叫routes物件,去定義每個場景。
還可以利用renderScene方法,導航欄可以根據指定的路由來渲染場景。
//專案的入口index.android.js頁面
import React, {Component} from 'react';
import {
AppRegistry,
StyleSheet,
View,
Navigator
} from 'react-native';
import FirstPage from './FirstPage'
export default class StudyGithub extends Component {
constructor(props) {
super(props);
this.state = {}
}
renderScene(route, navigator) {
let Component = route.component;
return (
<Component {...route.params} navigator={navigator}/>
);
}
render() {
return (
<Navigator
initialRoute={{
name: 'FirstPage',
component:FirstPage
}}
renderScene={(e, i)=>this.renderScene(e, i)}
/>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1
},
tabText: {
fontSize: 10,
color: 'black'
},
selectedTabText: {
fontSize: 10,
color: 'red'
},
icon: {
width: 22,
height: 22
},
page0: {
flex: 1,
backgroundColor: 'yellow'
},
page1: {
flex: 1,
backgroundColor: 'blue'
}
});
AppRegistry.registerComponent('StudyGithub', () => StudyGithub);
跳轉到第一個頁面FirstPage.js
import React, {Component} from 'react';
import {
StyleSheet,
Navigator,
TouchableOpacity,
Text,
View
} from 'react-native'
import SecondPage from './SecondPage'
export default class FirstPage extends Component {
constructor(props) {
super(props);
}
render() {
return (<View>
<TouchableOpacity
onPress={()=>this.jumpToNext()}>
<Text style={{fontSize:20,color: 'blue',margin:10}}>這是第一個頁面,點選可以跳轉到下一個頁面</Text>
</TouchableOpacity>
</View>);
}
/**
* 跳轉到下一個頁面
*/
jumpToNext() {
/* resetTo(route) 跳轉到指定的新場景,並重置路由棧*/
this.props.navigator.resetTo({
component: SecondPage,
/* 傳遞引數*/
params: {
text: 'jump to the second page'
}
});
}
}
從FirstPage跳轉到SecondPage.js頁面
import React, {Component} from 'react';
import {
StyleSheet,
Navigator,
TouchableOpacity,
Text,
View
} from 'react-native'
import FirstPage from './FirstPage'
export default class SecondPage extends Component {
constructor(props) {
super(props);
}
render() {
return (<View>
<Text style={{fontSize:20,color: 'red',margin:10}}>{this.props.text}</Text>
<TouchableOpacity
onPress={()=>this.jumpToFirst()}>
<Text style={{fontSize:20,color: 'red',margin:10}}>這是第二個頁面,點選可以回到上個頁面</Text>
</TouchableOpacity>
</View>);
}
/**
* 跳轉到下一個頁面
*/
jumpToFirst() {
/* push(route) 跳轉到新的場景,並且將場景入棧,你可以稍後用jump forward 跳轉回去*/
this.props.navigator.push({
component: FirstPage,
});
}
}