开始今天的话题以前,让咱们先来了解一下前端路由,Ajax诞生之后,解决了每次用户操做都要向服务器端发起请求重刷整个页面的问题,但随之而来的问题是没法保存Ajax操做状态,浏览器的前进后退功能也不可用,当下流行的两种解决方法是:前端
为了让history不只仅能回退到上一个页面,还能够回到上一个操做状态。HTML5新增了三个方法,其中两个是在history对象里的:react
window.onpopstate() 监听url的变化,会忽略hash的变化(hash变化有一个onhashchange事件),可是前面的两个事件不会触发它。android
总结:git
单页面应用或者Ajax操做记录状态用的就是hash和h5增长的history API,这就是react-router-dom 扩展的路由实现,也是web应用最经常使用的两种路由github
//引入必要的资源包 import ReactDom from 'react-dom'; import { Router, Route, hashHistory,IndexRoute} from 'react-router'; //路由页面配置 ReactDom.render( <Router history={hashHistory}> <Route path='/' component={Page}></Route> <Route path='/NewTask' component={NewTask} /> <Route path='/Redeem' component={Redeem} /> <Route path='/Rule' component={Rule} /> </Router> ,document.getElementById("app"));
当启动react项目时,会先生成好一个路由表,发生页面跳转时,react会根据地址到路由表中找到对应的处理页面或处理方法web
而动态路由不是做为一个项目运行的配置文件存储在外部,它在项目render的时候才开始定义,router的做者认为route应当和其它普通组件同样,它的做用不是提供路由配置,而是一个普通的UI组件npm
import React, { Component } from 'react'; import { Provider } from 'react-redux'; import { StatusBarIOS,Platform } from 'react-native'; import { createMemoryHistory, Router, IndexRoute, Route } from 'react-router'; import { createNavigatorRouter } from 'react-native-navigator-router'; <Provider store={store}> <Router history={createMemoryHistory('/')}> <Route path='/' component={createNavigatorRouter()}> <IndexRoute component={App} /> <Route path="/about" component={AllRoute} /> </Route> </Router> </Provider>
因 React Native 版本设计到0.44以后,原先的 RN 路由彻底失效了redux
运行直接报错,createMemoryHistory('/') 异常react-native
具体缘由仍是不太明白,应该是移除了react-router的使用方式,目前数组
首先从原理上,Navigator是用来做为组件之间的导航器。而缺少相似Router性质的东西时,最简单的办法是将下个组件(也叫场景Scene),直接告诉导航器。因此就须要在页面的上面引入下个组件
export default class SampleComponent extends React.Component { render() { let defaultName = 'FirstPageComponent';// 第一个要展现的组件 let defaultComponent = FirstPageComponent; return ( <Navigator initialRoute={{ name: defaultName, component: defaultComponent }} configureScene={(route) => { return Navigator.SceneConfigs.VerticalDownSwipeJump; }} renderScene={(route, navigator) => { let Component = route.component; return <Component {...route.params} navigator={navigator} /> }} /> ); } }
initialRoute={{ name: defaultName, component: defaultComponent }}
Navigator实现跳转,是经过Push和Pop方法,至关因而一个数组,每要跳到下个Scene(场景),就把下个页面push到这个数组中,当想要后退的时候,再把这个Pop出去
react-native 0.44 开始 再也不支持 Navigatior
NavigatorIOS使用
首先,建立一个 Home 组件,用来做为 NavigatorIOS 的根视图
视图部分:
render() { return ( <ScrollView style={styles.flex}> <View style={styles.container}> <Text onPress={this.goTo.bind(this)}>点我跳转详情</Text> </View> </ScrollView> ); }
样式部分:
const styles = StyleSheet.create({ flex: { flex: 1, marginTop: 65 }, listItem: { height: 40, marginLeft: 10, marginRight: 10, borderBottomWidth: 1, borderBottomColor: "#ddd", justifyContent: "center" }, listItemFont: { fontSize: 16 }, container: { justifyContent: "center", alignItems: "center" } });
而后咱们实例化一个 NavigatorIOS 并设置路由
class Test extends Component { render() { return ( <NavigatorIOS style={{ flex: 1 }} initialRoute={{ component: List,// 要跳转的页面 title: "列表",// 跳转页面导航栏标题 passProps: {} }} /> ); } }
return ( <View style={styles.container}> <TouchableOpacity onPress={() => {this.props.navigator.push({ component:Detail, // 须要跳转的页面 title:'详情' // 跳转页面导航栏标题 rightButtonTitle: "收藏",//跳转页面导航右侧按钮 onRightButtonPress: function() {//右侧按钮点击回调事件 alert("点击了收藏按钮。"); } })}} > <Text>点击跳转页面</Text> </TouchableOpacity> </View> );
因为前面介绍的几种路由方式要么随着RN版本更新已再也不支持,要么是单平台支持性;RN官方在0.44版本之后把导航路由集中到了react-navigation库里面,而且官方也事件使用react-navigation,少用第三方插件
添加react-navigation
该库包含三类组件:
npm install --save react-navigation
方法引用:
import { StackNavigator } from "react-navigation";
组件采用堆栈式的页面导航来实现各个界面跳转。它的构造函数:
StackNavigator(RouteConfigs, StackNavigatorConfig) RouteConfigs:页面路由配置 StackNavigatorConfig:路由参数配置
navigationOptions:配置StackNavigator的一些属性。 title:标题,若是设置了这个导航栏和标签栏的title就会变成同样的,不推荐使用 header:能够设置一些导航的属性,若是隐藏顶部导航栏只要将这个属性设置为null headerTitle:设置导航栏标题,推荐 headerBackTitle:设置跳转页面左侧返回箭头后面的文字,默认是上一个页面的标题。能够自定义,也能够设置为null headerTruncatedBackTitle:设置当上个页面标题不符合返回箭头后的文字时,默认改为"返回" headerRight:设置导航条右侧。能够是按钮或者其余视图控件 headerLeft:设置导航条左侧。能够是按钮或者其余视图控件 headerStyle:设置导航条的样式。背景色,宽高等 headerTitleStyle:设置导航栏文字样式 headerBackTitleStyle:设置导航栏‘返回’文字样式 headerTintColor:设置导航栏颜色 headerPressColorAndroid:安卓独有的设置颜色纹理,须要安卓版本大于5.0 gesturesEnabled:是否支持滑动返回手势,iOS默认支持,安卓默认关闭 screen:对应界面名称,须要填入import以后的页面 mode:定义跳转风格 card:使用iOS和安卓默认的风格 modal:iOS独有的使屏幕从底部画出。相似iOS的present效果 headerMode:返回上级页面时动画效果 float:iOS默认的效果 screen:滑动过程当中,整个页面都会返回 none:无动画 cardStyle:自定义设置跳转效果 transitionConfig: 自定义设置滑动返回的配置 onTransitionStart:当转换动画即将开始时被调用的功能 onTransitionEnd:当转换动画完成,将被调用的功能 path:路由中设置的路径的覆盖映射配置 initialRouteName:设置默认的页面组件,必须是上面已注册的页面组件 initialRouteParams:初始路由参数
能够只配置RouteConfigs参数
RouteConfigs参数表示各个页面路由配置,React开发中的 Router路由配置 ,它是让导航器知道须要导航的路由对应的页面
RN页面路由配置:
const AppIndex = StackNavigator( { Task: { screen: Task, //加载首屏须要在navigationOptions里面配置首页导航信息 navigationOptions: ({ navigation }) => ({ headerTitle: "首页", headerBackTitle: null }) }, NewTask: { screen: NewTask }, Redeem: { screen: Redeem }, Rule: { screen: Rule } } );
已经配置好导航器以及对应的路由页面了,可是要完成页面之间的跳转,还须要 navigation;
在导航器中的每个页面,都有 navigation 属性
页面的配置选项 navigationOptions 一般还能够在对应页面中去静态配置,好比在 Redeem 页面中 (注意:若是默认是首页的话就不要再页面中声明static navigationOptions了) class Redeem extends Component { static navigationOptions = ({ navigation }) => ({ headerTitle: `${navigation.state.params.title}`, headerRight: ( <View style={{ flexDirection: "row" }}> <Text style={{ color: "#333", marginRight: 13 }} onPress={() =>navigation.state.params ? navigation.state.params.jumpToRule() : null }> 兑换规则 </Text> </View> ) }); ..... } 通常子页面navigationOptions参数最好都在子页面里面去配置,不要在首页到导航参数里面配置,方便调用本类方法
调用这个方法能够跳转到导航器中的其余页面,此方法有三个参数
首先在页面须要跳转的地方声明navigate
const { navigate } = this.props.navigation;
而后经过点击事件调用navigate跳转
//首页跳转积分兑换页面 <TouchableOpacity style={styles.redeem} onPress={() => navigate("Redeem", { title: "积分兑换" })}> <Text style={styles.redeemText}>积分兑换</Text> </TouchableOpacity> //积分兑换页面跳转兑换规则页面 jumpToRule = () => { const { navigate } = this.props.navigation; navigate("Rule", { title: "积分兑换规则" }); }
state 里面包含有传递过来的参数 params 、 key 、路由名称 routeName
{ params: { param: 'i am the param' }, key: 'id-1500546317301-1', routeName: 'Redeem' }
使用:
headerTitle: `${navigation.state.params.title}`
更改当前页面路由的参数,好比能够用来更新头部的按钮或者标题
setParams的使用:
//导航右侧按钮 点击调用原本方法 headerRight: ( <View style={{ flexDirection: "row" }}> <Text style={{ color: "#333", marginRight: 13 }} onPress={() => navigation.state.params ? navigation.state.params.jumpToRule() : null }> 兑换规则 </Text> </View> )
说明:
若是导航栏上的的按钮点击是须要调用本类方法时不能直接this.jumpToRule(),须要在声明周期的componentDidMount中经过navigation中的setParams把函数注册到导航器中
componentDidMount() { this.props.navigation.setParams({ jumpToRule: this.jumpToRule }); }
能够不传,也能够传参数,还能够传 null
this.props.navigation.goBack(); // 回退到上一个页面
this.props.navigation.goBack(null); // 回退到任意一个页面
this.props.navigation.goBack('Home'); // 回退到Home页面
dispatch - 发送一个action
组件采用堆栈式的页面导航来实现各个界面跳转。它的构造函数:
TabNavigator(RouteConfigs, TabNavigatorConfig) RouteConfigs:页面tab配置 TabNavigatorConfig:参数配置
screen:和导航的功能是同样的,对应界面名称,能够在其余页面经过这个screen传值和跳转。 navigationOptions:配置TabNavigator的一些属性 title:标题,会同时设置导航条和标签栏的title tabBarVisible:是否隐藏标签栏。默认不隐藏(true) tabBarIcon:设置标签栏的图标。须要给每一个都设置 tabBarLabel:设置标签栏的title。推荐 导航栏配置 tabBarPosition:设置tabbar的位置,iOS默认在底部,安卓默认在顶部。(属性值:'top','bottom') swipeEnabled:是否容许在标签之间进行滑动 animationEnabled:是否在更改标签时显示动画 lazy:是否根据须要懒惰呈现标签,而不是提早,意思是在app打开的时候将底部标签栏所有加载,默认false,推荐为true trueinitialRouteName: 设置默认的页面组件 backBehavior:按 back 键是否跳转到第一个Tab(首页), none 为不跳转 tabBarOptions:配置标签栏的一些属性iOS属性 activeTintColor:label和icon的前景色 活跃状态下 activeBackgroundColor:label和icon的背景色 活跃状态下 inactiveTintColor:label和icon的前景色 不活跃状态下 inactiveBackgroundColor:label和icon的背景色 不活跃状态下 showLabel:是否显示label,默认开启 style:tabbar的样式 labelStyle:label的样式安卓属性 activeTintColor:label和icon的前景色 活跃状态下 inactiveTintColor:label和icon的前景色 不活跃状态下 showIcon:是否显示图标,默认关闭 showLabel:是否显示label,默认开启 style:tabbar的样式 labelStyle:label的样式 upperCaseLabel:是否使标签大写,默认为true pressColor:material涟漪效果的颜色(安卓版本须要大于5.0) pressOpacity:按压标签的透明度变化(安卓版本须要小于5.0) scrollEnabled:是否启用可滚动选项卡 tabStyle:tab的样式 indicatorStyle:标签指示器的样式对象(选项卡底部的行)。安卓底部会多出一条线,能够将height设置为0来暂时解决这个问题 labelStyle:label的样式 iconStyle:图标样式
导入必要组件:
import { TabNavigator } from "react-navigation"; import Home from "./category/Home"; import Feedback from "./category/feedback/feedback";
定义TabNavigator:
const MyTab = TabNavigator( { Home: { screen: Home, navigationOptions: ({ navigation }) => ({ headerTitle: "首页", tabBarLabel: "首页", headerBackTitle: null }) }, Feed: { screen: Feedback, navigationOptions: ({ navigation }) => ({ headerTitle: "意见反馈", tabBarLabel: "个人", headerBackTitle: null, }) } }, { tabBarComponent: TabBarBottom, tabBarPosition: "bottom", //设置tabbar的位置,iOS默认在底部,安卓默认在顶部。(属性值:'top','bottom') swipeEnabled: true, //是否容许在标签之间滑动 animationEnabled: false, //是否在更改标签时显示动画 lazy: true, //是否根据须要懒惰呈现标签,而不是提早制做,意思是在app打开的时候将底部标签栏所有加载,默认false,推荐改为true tabBarOptions: { activeTintColor: "#ff552e", //label和icon的前景色 活跃状态下(选中) // activeBackgroundColor:'blue',//label和icon的背景色 活跃状态下 inactiveTintColor: "#333", //label和icon的前景色 不活跃状态下 showLabel: true, //是否显示label,默认开启 showIcon: true, // android 默认不显示 icon, 须要设置为 true 才会显示 style: { backgroundColor: "#ffffff" }, //tabbar的样式 labelStyle: { fontSize: 14 // 文字大小 } } } );
const MyTab = TabNavigator( { Home: { screen: Home, navigationOptions: ({ navigation }) => ({ headerTitle: "首页", tabBarLabel: "首页", headerBackTitle: null, tabBarIcon: ({ tintColor }) => ( <Image style={styles.imageStyle} source={ tintColor == "#ff552e" ? require("./img/yingxiao/ac-jingxuan.png") : require("./img/yingxiao/jingxuan.png") } /> ) }) }, Feed: { screen: Feedback, navigationOptions: ({ navigation }) => ({ headerTitle: "意见反馈", tabBarLabel: "个人", headerBackTitle: null, headerRight: ( <Text style={{ color: "#333", marginRight: 14, fontSize: 16 }} onPress={() => navigation.state.params ? navigation.state.params.submit() : null }> 提交 </Text> ), tabBarIcon: ({ tintColor }) => ( <Image style={styles.imageStyle} source={ tintColor == "#ff552e" ? require("./img/yingxiao/ac-laidiantong.png") : require("./img/yingxiao/laidiantong.png") } /> ) }) } }, { tabBarComponent: TabBarBottom, tabBarPosition: "bottom", //设置tabbar的位置,iOS默认在底部,安卓默认在顶部。(属性值:'top','bottom') swipeEnabled: true, //是否容许在标签之间滑动 animationEnabled: false, //是否在更改标签时显示动画 lazy: true, //是否根据须要懒惰呈现标签,而不是提早制做,意思是在app打开的时候将底部标签栏所有加载,默认false,推荐改为true tabBarOptions: { activeTintColor: "#ff552e", //label和icon的前景色 活跃状态下(选中) // activeBackgroundColor:'blue',//label和icon的背景色 活跃状态下 inactiveTintColor: "#333", //label和icon的前景色 不活跃状态下 showLabel: true, //是否显示label,默认开启 showIcon: true, // android 默认不显示 icon, 须要设置为 true 才会显示 style: { backgroundColor: "#ffffff" }, //tabbar的样式 labelStyle: { fontSize: 14 // 文字大小 } } } ); const AppIndex = StackNavigator( { Main: { screen: MyTab }, Task: { screen: Task }, NewTask: { screen: NewTask }, Redeem: { screen: Redeem }, Rule: { screen: Rule }, Test: { screen: Test } }, { initialRouteName: "Task", // 默认显示界面 navigationOptions: { headerTitle: "每日任务", headerBackTitle: null, // headerBackTitle: "返回", headerTintColor: "#333", cardStack: { gesturesEnabled: true //是否容许右滑返回,在iOS上默认为true,在Android上默认为false } }, // mode: "card", // 页面切换模式, 左右是card(至关于iOS中的push效果), 上下是modal(至关于iOS中的modal效果) headerMode: "screen", // 导航栏的显示模式, screen: 有渐变透明效果, float: 无透明效果, none: 隐藏导航栏 onTransitionStart: () => {}, // 回调 onTransitionEnd: () => {} // 回调 } );