RN(react-native)踩坑实录--页面跳转
页面跳转
移动应用基本不会只由一个页面组成。管理多个页面的呈现、跳转的组件就是我们通常所说的导航器(navigator)。社区今后主推的方案是一个单独的导航库react-navigation,它的使用十分简单。React Navigation 中的视图是原生组件,同时用到了运行在原生线程上的Animated动画库,因而性能表现十分流畅。此外其动画形式和手势都非常便于定制。
React Navigation
React Navigation 提供了简单易用的跨平台导航方案,在 iOS 和 Android 上都可以进行翻页式、tab 选项卡式和抽屉式的导航布局。
yarn add react-navigation
添加welecome页面
以之前的demo为例,在目录下新建文件夹js,在该文件夹下新建Welecome.js文件,添加以下代码。
//Welecome.js
import React, { Component } from 'react'
import { ImageBackground } from "react-native";
export default class WelecomeScreen extends React.Component{
static navigationOptions = {
header:null,
}
constructor(props){
super(props);
this.Time = this.Time.bind(this)
}
componentDidMount(){
this.Time()
}
Time(){
setTimeout(()=>{
this.props.navigation.navigate('Home')
},2000)//定时两秒后自动跳转到主页.
}
componentWillUnmount(){
clearTimeout();
}
render(){
return(
<ImageBackground style={{width: '100%', height: '100%'}} source={require('./img/1.jpg')} resizeMode='stretch'>
</ImageBackground>
)
}
}
主页面
在js文件夹下新建Home.js,将之前App.js中的代码剪切过去。
然后在App.js中添加以下代码:
//App.js
import { createAppContainer, createStackNavigator,StackActions, NavigationActions } from 'react-navigation'; // Version can be specified in package.json
import MainScreen from './js/Home'
import WelecomeScreen from './js/Welecome'
const MainNavigationStack = createStackNavigator({//页面路由
Welecome:{
screen:WelecomeScreen,
},
Home:{
screen:MainScreen
}
},{
initialRouteName:'Welecome',
defaultNavigationOptions:{
header:null,
}
})
export default createAppContainer(MainNavigationStack);