问题描述:react
使用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> } }