這是一個控制視圖跳轉(zhuǎn)的組件(類似于Android原生中的Activity之間的跳轉(zhuǎn))
自己的理解和實踐
RN會先加載index.android.js中的組件,這樣,我們就在該文件中只實現(xiàn)路由的跳轉(zhuǎn)。
index.android.js
export default class StudyNavigationApp extends Component {
render() {
return (
<Navigator
initialRoute={{title:'My initial Scene',index:0}}
renderScene={(route,navigator)=>{
switch (route.index){
case 0:
return <MyScene navigator={navigator}/>
break;
case 1:
return <ComponentStudy0 navigator={navigator}/>
break;
}
}
}
/>
);
}
}
這里我們默認了index為0的時候需要加載MyScene:
class MyScene extends Component {
render() {
return (
<View>
<TouchableHighlight onPress={()=>this.props.navigator.push({index:1})}>
<Text>
Hi,My name is hehe
</Text>
</TouchableHighlight>
</View>
)
}
}
在上面的默認加載index為0的時候加載MyScene的時候,傳入了navigator參數(shù),并在MyScene中通過props使用。
這樣,每次新建一個視圖的的時候,只要在跳轉(zhuǎn)的時候,指明其index就行了。
Note:
外部定義需要引入的class需要被export default進行修飾
監(jiān)聽后退按鍵
constructor(props) {
super(props);
this.goBack = this.goBack.bind(this);
}
componentDidMount() {
BackAndroid.addEventListener('hardwareBackPress', this.goBack);
}
componentWillUnMount() {
BackAndroid.removeEventListener('hardwareBackPress', this.goBack);
}
當然,你需要先引入BackAndroid,然后在Navigator的屬性renderScene中實例化_navigator.
<Navigator
initialRoute={{title:'RN study',index:0}}
renderScene={(route,navigator)=>{
_navigator = navigator;
}
....