美文网首页react-nativeReactNative
React Navigation 自认比较好的navigator

React Navigation 自认比较好的navigator

作者: 大侠走一波 | 来源:发表于2017-03-06 13:24 被阅读1806次

    这篇文章主要的内容是自定义的navigator,因为在某些情况下,默认的StackNavigator和TabNavigator无法满足需求(TabNavigator在android环境下默认是基于scrollView的滚动样式,会导致一些第三方组件无法正常运行,并且也不好修改),所以就需要我们按照自己的想法来自定一个navigator。

    Custom Navigators

    一个导航器可以是一个任何拥有router的React组件,下面是一个简单的例子:

    class MyNavigator extends React.Component {
      static router = MyRouter;
      render() {
        const { state, dispatch } = this.props.navigation;
        const { routes, index } = state;
    
        // Figure out what to render based on the navigation state and the router:
        const Component = MyRouter.getComponentForState(state);
    
       // The state of the active child screen can be found at routes[index]
        let childNavigation = { dispatch, state: routes[index] };
    
        // If we want, we can also tinker with the dispatch function here, to limit
        // or augment our children's actions
        // Assuming our children want the convenience of calling .navigate() and so on,
        // we should call addNavigationHelpers to augment our navigation prop:
        childNavigation = addNavigationHelpers(childNavigation);
    
        return <Component navigation={childNavigation} />;
      }
    }
    
    

    自己模仿示例代码自定义了一个TabBar

    /**
     * Created by Guodada on 2017/3/2.
     */
    import React from 'react';
    import {
        Button,
        Platform,
        ScrollView,
        StyleSheet,
        Text,
        TouchableOpacity,
        View,
        Dimensions,
        TouchableHighlight,
    
    } from 'react-native';
    
    import {
        createNavigator,
        createNavigationContainer,
        TabRouter,
        addNavigationHelpers,
    } from 'react-navigation';
    
    //导入界面
    import Home from './Home/Home';
    import Find from './Find/Find';
    import Me from './Me/Me';
    import Contacts from './Contacts/Contacts';
    
    const {width,height} = Dimensions.get('window');
    
    
    //设置每个标签
    const CustomTabBar = ({
        navigation
    }) => {
        console.log('TabBar navigation ============'+ navigation.state.index);
    
        const {routes} = navigation.state;
        let selectedIndex = navigation.state.index;
        let isSelected = false;
    
        return (
    
            <View style={styles.tabContainer}>
                {
                    routes.map((route,index) =>{
    
                        //如果当前选中该index的router
                        selectedIndex === index?isSelected = true:isSelected = false;
    
                        //显示不同外观
                        let textColor = isSelected?'blue':'gray';
    
                        return (
                            <TouchableOpacity
                                onPress={() => {
                              navigation.navigate(route.routeName);
                          }}
                                key={route.routeName}
                                style={styles.tab}
                            >
                                <Text style={{color:textColor,fontSize:12}}>{route.routeName}</Text>
                            </TouchableOpacity>
                        )
                    })}
            </View>
        );
    };
    
    //设置TabBar
    const CustomTabView = ({
        router,
        navigation
    }) => {
        console.log('navigation ============>>>>>'+ navigation.state.index);
    
        const {routes,index} = navigation.state;
        const ActiveScreen = router.getComponentForState(navigation.state);
    
        return (
            <View style={styles.container}>
                <ActiveScreen
                    navigation={addNavigationHelpers({
                        ...navigation,
                        state:routes[index],
                        })}
                />
                <CustomTabBar navigation={navigation}/>
    
            </View>
        );
    };
    
    //自定义导航路由
    const CustomTabRouter = TabRouter({
    
            Home:{
                screen:Home,
            },
            Me:{
                screen:Me,
            },
            Contacts:{
                screen:Contacts,
            },
            Find:{
                screen:Find,
            },
        },                   {
            initialRouteName:'Home'
        }
    );
    
    //创建自定义TabBar
    const CustomTabs = createNavigationContainer(createNavigator(CustomTabRouter)(CustomTabView));
    
    const styles = StyleSheet.create({
        container: {
            flex:1,
            justifyContent:'center'
        },
        tabContainer: {
            flexDirection: 'row',
            height: 48,
            borderTopWidth:1,
            borderColor:'lightgray'
        },
        tab: {
            flex: 1,
            alignItems: 'center',
            justifyContent: 'flex-end',
            margin: 4,
            borderWidth: 1,
            borderColor: '#ddd',
            borderRadius: 4,
        }
    });
    
    
    export default CustomTabs;
    

    文末彩蛋,传值方式
    从前往后:

     <Button       title='Press me!'
                        onPress={() => navigate('Home_2',{passValue:(value)=> console.log('The value passed by child scene is '+ value),name:'jack'})}
                        color='black'
                    />
    

    从后往前:

     <Button title='<Back'
                  onPress={()=> {
                  goBack();
                  state.params.passValue('This is the value needs to pass front scene');
                            }}
                    />
    

    相关文章

      网友评论

      • 半块:自定义这种会不断的调用render函数 可有办法解决这个问题?
        c078e1e4b3c9:我也想知道这个解决方法啊
      • 出来吧孩子:大侠,有没有了解过graphql,apollo 关于api的包装,现在没有中文文档,有空给咱小菜翻译翻译
        大侠走一波:这个没用到过啊,我只是研究到什么就顺手写什么的。
      • Juice_gg:楼主什么时候翻译一下哎结合redux使用的部分
        Juice_gg:@大侠走一波 嗯,那个例子已经看了,差不多理解了
        大侠走一波:还有关于redux,该组件在github上的demo中有一个结合redux的例子,做了一个简易的login功能界面,你可以下载下来看一看。我觉得那个例子挺好,很简单
        大侠走一波:@Juice_gg 抽时间吧 最近手头有别的活,RN现在暂时没有继续学习
      • 出来吧孩子:大神,知道不知道deep Linking这么获取参数,github上没api,难道就是获取到url后解析?
        大侠走一波:@神之指 不好意思 我还没涉及这方面

      本文标题:React Navigation 自认比较好的navigator

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