ReactNative学习笔记二之StackNavigator

作者: mymdeep | 来源:发表于2017-06-28 10:25 被阅读409次

    这一节主要是介绍react-navigation的StackNavigator,我当前使用的版本是1.0.0-beta.11,与之前的语法较有不同。

    安装以及相关问题

    首先要想使用react-navigation,需要先进行安装:

     npm install --save react-navigation
    

    问题一

    有时候在安装完,会出现react不能使用的情况,需要重新安装一下react

     npm install -g yarn react-native-cli
    

    问题二

    如果报出以下问题:

    image.png

    可以替换下版本:

    yarn add react@16.0.0-alpha.12
    

    问题三

    如果 'React/RCTBundleURLProvider.h' file not found
    左侧点击跟项目目录 -> 选择右侧 Build Settings -> 选择 All & Combined -> 搜索框输入 Always Search User Paths -> 将 Always Search User Paths 设置为 Yes -> Clean -> Build


    5951e4a8885d4c37a63a0a275f893c99-image.png

    使用

    在开始介绍之前先放一个首页的图:

    现在放一下代码:

    import React from 'react';
    import {
        AppRegistry,
        StyleSheet,
        Text,View,Button,
    } from 'react-native';
    import { StackNavigator } from 'react-navigation';
    import Detail from './Detail';
    import UserCenter from './UserCenter';
    
    class HomeScreen extends React.Component {
    
        static navigationOptions = ({navigation}) => {
        return{
                title:'我的产品',
            headerTitleStyle:{
                alignSelf:'center',
                color: '#388e3c'
            },
                backTitle: '返回',  // 左上角返回键文字
                style: {
                    backgroundColor: '#0d47a1'
                },
                titleStyle: {
                    color: '#388e3c'
                },
            headerRight: (
                <Button
                    title="个人中心"
    
                    onPress={() => navigation.navigate('UserCenter',{user:'我的App'})}
                />
            ),
    
            cardStack: {
                gesturesEnabled: true
            },
        }
    
        };
    
        render() {
            const { navigate } = this.props.navigation;
            return (
                <View>
                    <Text>搜索</Text>
                    <Button
                        onPress={() => navigate('DetailPage',{user:'我的App'})}
                        title="我的App"/>
                </View>
            );
        }
    }
    
    const styles = StyleSheet.create({
        RightButton: {
            justifyContent: 'center',
            alignItems: 'center',
            backgroundColor: '#F5FCFF',
            marginRight:10
        },
    
    });
    
    const SimpleApp = StackNavigator({
        Home: {screen: HomeScreen},
        UserCenter: {screen: UserCenter},
        DetailPage:{screen:Detail}
    
           
    
    }, {
        initialRouteName: 'Home', // 默认显示界面
    
        mode: 'card',  // 页面切换模式, 左右是card(相当于iOS中的push效果), 上下是modal(相当于iOS中的modal效果)
        headerMode: 'screen', // 导航栏的显示模式, screen: 有渐变透明效果, float: 无透明效果, none: 隐藏导航栏
        onTransitionStart: ()=>{ console.log('导航栏切换开始'); },  // 回调
        onTransitionEnd: ()=>{ console.log('导航栏切换结束'); }  // 回调
    });
    
    export default SimpleApp;
    
    

    首先需要介绍的是设置可跳转的界面,在这里我们主要有三个Home,UserCenter,DetailPage每个界面对应了一个js文件,需要提前import进来。
    但需要跳转的时候,只要找到this.props.navigation,执行跳转方法即可navigate('DetailPage',{user:'我的App'})
    其中DetailPage是对应的界面,后面是可以传递过去的数据,没有数据也可以不用传递。
    在这里需要重点介绍的是navigationOptions,这个的设置有两种写法,一种比较简单,不需要传参进来:

        static navigationOptions =  {
       
                title:'我的产品',
            headerTitleStyle:{
                alignSelf:'center',
                color: '#388e3c'
            },
                 
    
        };
    

    但是由于,我们可能会在左右按钮的时候设置一些跳转,这时就需要navigation,那么这是可以这样写:

        static navigationOptions = ({navigation}) => {
        return{
                title:'我的产品',
            headerTitleStyle:{
                alignSelf:'center',
                color: '#388e3c'
            },
                backTitle: '返回',  // 左上角返回键文字
                style: {
                    backgroundColor: '#0d47a1'
                },
                titleStyle: {
                    color: '#388e3c'
                },
            headerRight: (
                <Button
                    title="个人中心"
    
                    onPress={() => navigation.navigate('UserCenter',{user:'我的App'})}
                />
            ),
    
            cardStack: {
                gesturesEnabled: true
            },
        }
    
        };
    

    再看一下另一个界面怎么写的(UserCenter):

    import React, { Component } from 'react';
    import {
        AppRegistry,
        StyleSheet,
        Text,
        View
    } from 'react-native';
    export default class UserCenter extends Component {
        render() {
            return (
                <View style={styles.container}>
                    <Text style={styles.welcome}>
                       这里是用户中心!
                    </Text>
                    <Text style={styles.instructions}>
                        但是还没有内容
                    </Text>
                    <Text style={styles.instructions}>
                        因为,{'\n'}
                       没有登录接口
                    </Text>
                </View>
            );
        }
    }
    
    const styles = StyleSheet.create({
        container: {
            flex: 1,
            justifyContent: 'center',
            alignItems: 'center',
            backgroundColor: '#F5FCFF',
        },
        welcome: {
            fontSize: 20,
            textAlign: 'center',
            margin: 10,
        },
        instructions: {
            textAlign: 'center',
            color: '#333333',
            marginBottom: 5,
        },
    });
    

    接口属性

    对于StackNavigatorConfig的一些接口,主要分为两部分,一部分是StackNavigatorConfig,一部分是Screen Navigation Options

    StackNavigatorConfig

    StackNavigatorConfig也就是需要在const SimpleApp = StackNavigator(screen,StackNavigatorConfig);中设置的:

    Options for the router:

    • initialRouteName - Sets the default screen of the stack. Must match one of the keys in route configs.
    • initialRouteParams - The params for the initial route
    • navigationOptions - Default navigation options to use for screens
    • paths - A mapping of overrides for the paths set in the route configs

    Visual options:

    • mode - Defines the style for rendering and transitions:

        card - Use the standard iOS and Android screen transitions. This is the default.
       
        modal - Make the screens slide in from the bottom which is a common iOS pattern. Only works on iOS, has no effect on Android.
      
    • headerMode - Specifies how the header should be rendered:

        float - Render a single header that stays at the top and animates as screens are changed. This is a common pattern on iOS.
      
        screen - Each screen has a header attached to it and the header fades in and out together with the screen. This is a common pattern on Android.
         none - No header will be rendered.
      
    • cardStyle - Use this prop to override or extend the default style for an individual card in stack.

    • transitionConfig - Function to return an object that overrides default screen transitions.

    • onTransitionStart - Function to be invoked when the card transition animation is about to start.

    • onTransitionEnd - Function to be invoked once the card transition animation completes.

    Screen Navigation Options

    • title
      String that can be used as a fallback for headerTitle and tabBarLabel
    • header
      React Element or a function that given HeaderProps returns a React Element, to display as a header. Setting to null hides header.
    • headerTitle
      String or React Element used by the header. Defaults to scene title
    • headerBackTitle
      Title string used by the back button on iOS or null to disable label. Defaults to scene title
    • headerTruncatedBackTitle
      Title string used by the back button when headerBackTitle doesn't fit on the screen. "Back" by default.
    • headerRight
      React Element to display on the right side of the header
    • headerLeft
      React Element to display on the left side of the header
    • headerStyle
      Style object for the header
    • headerTitleStyle
      Style object for the title component
    • headerBackTitleStyle
      Style object for the back title
    • headerTintColor
      Tint color for the header
    • headerPressColorAndroid
      Color for material ripple (Android >= 5.0 only)
    • gesturesEnabled
      Whether you can use gestures to dismiss this screen. Defaults to true on iOS, false on Android.
      如果你也做ReactNative开发,并对ReactNative感兴趣,欢迎关注我的公众号,加入我们的讨论群:

    相关文章

      网友评论

      • 06407931f5c5:你好,有没有项目的demo可以参考一下??
      • will86:很详细的了。想请教个问题,页面跳转时,新旧📃的生命周期是如何的呢,能否讲解一下
        mymdeep:@will86 你可以关注我的公众号,查看一下最新的文章,感谢您的留言

      本文标题: ReactNative学习笔记二之StackNavigator

      本文链接:https://www.haomeiwen.com/subject/anzycxtx.html