问题描述:使用createMaterialTopTabNavigator创建顶部导航栏,希望实现切换到指定的Tab再获取数据,查看官方文档只能找到tabBarOnPress 方法监听点击回调,但是无法监听滑动切换import React from ‘react’;import {DeviceEventEmitter,View} from ‘react-native’;import { createMaterialTopTabNavigator } from ‘react-navigation’;export default class TestPage extends React.Component{ constructor(props) { super(props); this.topTabList = [‘All’,‘Java’, ‘Javascript’, ‘PHP’]; } getTopBar() { let topBars = {} this.topTabList.forEach((item, index) => { topBars[‘TopBar’ + item] = { screen: (props)=><ChildComponent {…props} tabName={item} InitTabName={this.topTabList[0]}/>, navigationOptions: { title: item, } } }) return topBars } getTopTabList(){ if(!this.createTopNavigator){ this.createTopNavigator = createMaterialTopTabNavigator( this.getTopBar(), { //code… } ); } return this.createTopNavigator; } render(){ const TopTabList = this.getTopTabList(); // 在导航栏组件render位置使用onNavigationStateChange方法监听顶部导航切换-可监听滑动+点击 return <View> <TopTabList onNavigationStateChange={(prevState, currentState)=>{ let {index} = currentState; let TabName = currentState.routes[index].routeName; TabName = TabName.split(’’)[1]; //触发事件监听器,更新列表数据 //tip:如果希望切换已经加载过一次之后不重新获取数据,可以通过setParams设一个flag,判断flag是否需要触发监听器 DeviceEventEmitter.emit(‘TabChange’,TabName); }} /> </View> }}class ChildComponent extends React.Component{ constructor(props){ super(props); this.tabName= this.props.tabName; //当前tabName this.InitTabName = this.props.InitTabName; //初始化列表 } componentWillMount(){ // 加载初始化Tab列表 if(this.storeName===this.InitTabName){ this.updateList(); } // 监听Tab切换 this.TopBarChangeListener = DeviceEventEmitter.addListener(‘TabChange’,tabName=>{ if(this.tabName===tabName){ //更新列表 this.updateList(); } }) } // 更新列表 updateList(){ let {navigation} = this.props; navigation.setParams({hasList:true}); this.loadData(); } loadData(){ //Send Request } componentWillUnmount(){ //移除事件监听器 if(this.TopBarChangeListener){ this.TopBarChangeListener.remove(); } } } render(){ return <View> {/* code… */} </View> }}