React Native 多层嵌套导航器页面跳转的解决方案
前言
题主在使用React native在对毕设进行界面设计的时候,使用到了多层导航器嵌套,类似下图这样的,BottomTab嵌套TopTab,然后在TopTab里面在嵌套一层TopTab
问题
这时在第二层TopTab又或者在第三层TopTab添加点击事件的时候并不会根据路由页面进行相应的跳转
解决方案
我一开始在网上找了许久,都没有对这种情况有详细的解决方案,正当绝望之际,突然在React Native的中文网站上发现了这几段话:
上面的那几段话的大概意思是如果想要在子页面进行跳转的话就必须把父导航器的router往下进行传递,这样才能在子页面中实现跟父导航器一样的跳转效果,因此我将最表面的this.props.navigation当作router传递给TopTab(即第二层),然后再相应的顶部导航器页面中设置相应的变量来接受由上一层传递过来的this.props.navigation,以此类推多层嵌套导航器,下面直接上代码:
// 这里是底部导航栏的路由页面(第一层)
import React, { Component } from 'react';
import { Text, View, Image, ShadowPropTypesIOS } from 'react-native';
//import Ionicons from 'react-native-vector-icons/Ionicons'
import { createAppContainer } from 'react-navigation';
import { createBottomTabNavigator } from 'react-navigation-tabs';
import shouye from './shouye';
const HomePage = createAppContainer(
createBottomTabNavigator(
{
Home: {
screen: shouye,
navigationOptions:
{
tabBarPosition: 'bottom',
tabBarLabel: '首页',
showLabel:false,
tabBarIcon: ({tintColor, focused}) => {
let imgSrc = focused
? require('../picture/yemian2.png')
: require('../picture/yemian.png');
return (<Image source={imgSrc} style={{height: 26 ,width:26}}/>);
}
},
},
)
);
export default HomePage;
//这里是从底部导航栏跳转过来的页面这里还是第一层
import TopTab2 from './category/TopTab2'
import React, {Component} from 'react';
import {Animated, FlatList, Text, View, StyleSheet,Image, ImageBackground,StatusBar,DeviceEventEmitter} from 'react-native';
import StickyHeader from "./StickyHeader";
import { ScrollView } from 'react-native-gesture-handler';
export default class shouye extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<View>
<ScrollView>
<TopTab2 navigation={this.props.navigation}/>
//这里将表层的this.props.navigation即router往下一层进行传递
//这里的TopTab2是顶部导航栏的路由页面
</ScrollView>
</View>
)
}
}
shouye.router=TopTab2.router
//这里是从刚刚的顶部导航栏跳转过来的页面(第二层)
import React, { Component } from 'react';
import { Image,StyleSheet,Text,View,FlatList,Button,componentWillMount,DeviceEventEmitter } from 'react-native';
import CardView from 'react-native-cardview'
import ActionButton from 'react-native-action-button';
import Icon from 'react-native-vector-icons/Ionicons';
import { TouchableOpacity, ScrollView } from 'react-native-gesture-handler';
import LazyImage from 'animated-lazy-image';
export default class guangzhu extends Component {
constructor(props) {
super(props);
}
render() {
const router=this.props.navigation
//这里设置一个变量router来接收由上个页面传递过来的router
return (
<TouchableOpacity onPress={()=> router.navigate('gossip2')}>
//这里直接使用router.navigate直接进行跳转就可以了
<LazyImage source={item.src} style={{borderRadius:35,width:70,height:70}}/>
</TouchableOpacity>
);
}
}
Tips:写这行代码<TopTab2 navigation={this.props.navigation}/>
的时候模拟器可能会报错,把node.js终端关掉再重启一次项目就可以了
后话
由于题主刚学React Native不到几个月的时间,对于这种嵌套导航器页面也只能想出这种方案了,其实一开始的话还想过利用广播机制又或者react native redux,但这种方案对于这种小型项目十分适合,到了公司的一些大型项目可能就需要redux了。