如何重新加载视图点击React Native中的TabNavigator

时间:2017-09-19 12:35:21

标签: reactjs react-native react-native-android react-navigation tabnavigator

我希望每次用户改变标签时重新加载tabNavigator。当用户更改选项卡时,不会调用本机的生命周期方法。那怎样才能在TabNavigator中重新加载标签:

以下示例有两个标签:1)主页2)事件。现在我想在用户从主页选项卡返回时刷新事件选项卡。

EXPO LINK: Expo Tab Navigator

代码:

import React, {Component} from 'react';
import  {View, StyleSheet, Image, FlatList, ScrollView, Dimensions } from 'react-native';
import { Button, List, ListItem, Card  } from 'react-native-elements' // 0.15.0
//import { Constants } from 'expo';
import { TabNavigator, StackNavigator } from 'react-navigation'; // 1.0.0-beta.11

//image screen width and height defs
const windowWidth = Dimensions.get('window').width;
const windowHeight = Dimensions.get('window').height;


export default class App extends Component {
  render() {
    //const { navigate } = this.props.navigation;
    return (
      <TabsNav  />
      )
  }
  }


class MyHomeScreen extends Component {
  render() {
    return (
      <View>
            <Image
              resizeMode="cover"
              style={{    width: windowWidth * .85,    height: windowHeight * 0.3}}
              source={{uri: 'http://www.ajaxlibrary.ca/sites/default/files/media/logo.png?s358127d1501607090'}}
            />
            <Button
              onPress={() => this.props.navigation.navigate('Notifications')}
              title="Go to notifications"
            />
      </View>

    );
  }
}

class AplEvents extends Component {
  static navigationOptions = {
    tabBarLabel: 'Events List',
    tabBarIcon: ({ tintColor }) => (
      <Image
        source={{uri: 'https://facebook.github.io/react/img/logo_og.png'}}
        style={[styles.icon, {tintColor: tintColor}]}
      />
    ),
  };

    constructor(props) {
    super(props);

    this.state = {
      data: [],
      error: null,
    };
  }

  // when component mounts run the function fetch
  componentDidMount() {
    this.makeRemoteRequest();
  }

  makeRemoteRequest = () => {
    const url = `http://www.ajaxlibrary.ca/?q=calendar-test`;

    fetch(url)
      .then((res) => res.json())
      .then((res) => {
        this.setState({
          data: [...this.state.data, ...res.nodes],
          error: res.error || null,
        });
      })
      .catch(error => {
        this.setState( error );
      });
  };


  render() {
    const { navigate } = this.props.navigation;
    return (
         <List containerStyle={{ marginTop: 0, borderTopWidth: 0, borderBottomWidth: 0 }}>
        <FlatList
          data={this.state.data}
          renderItem={({ item }) => (
            <ListItem
              //squareAvatar
              title={`${item.node.title}\n${item.node.Program_Location}`}
              subtitle={item.node.Next_Session}
              avatar={{ uri: item.node.Image }}
              containerStyle={{ borderBottomWidth: 0 }}
             // save params to pass to detailed events screen
              onPress={() => navigate('Details', {title: `${item.node.title}`,
                                                body: `${item.node.Body}`,
                                                date: `${item.node.Date}`,
                                                Next_Session: `${item.node.Next_Session}`,
                                                Program_Location: `${item.node.Program_Location}`,
                                                Nid: `${item.node.Nid}`,
                                                Image: `${item.node.Image}`,
                                                Run_Time: `${item.node.Run_Time}`})}
            />
          )}
          keyExtractor={item => item.node.Nid}
        />
        </List>
    );
  }
}

class EventDetails extends Component {
      static navigationOptions = {
    title: 'EventDetails'
  };
  render() {
    const { params } = this.props.navigation.state;

    let pic = {
      uri: `${params.Image}`
    };
    //const pic = { params.Image };
    return (

          <ScrollView>

              <Card
                title={params.title}
              >
                  <Image
                      resizeMode="cover"
                       style={{    width: windowWidth * .85,    height: windowHeight * 0.3}}
                      source={pic}
                  />

                  <Button style={{marginTop: 10}}
                      icon={{name: 'date-range'}}
                      backgroundColor='#03A9F4'
                      fontFamily='Lato'
                      buttonStyle={{borderRadius: 0, marginLeft: 0, marginRight: 0, marginBottom: 0}}
                      title='Add to Calendar'
                  />
                    <ListItem
                     title="Event Description"
                     subtitle={params.body}
                     hideChevron='true'
                    />
                    <ListItem
                     title="Date"
                     subtitle={`${params.Next_Session}\n Run Time - ${params.Run_Time}`}
                     hideChevron='true'
                    />
                    <ListItem
                     title="Location"
                     subtitle={params.Program_Location}
                     hideChevron='true'
                    />
              </Card>
          </ScrollView>
    );
  }
}


const styles = StyleSheet.create({
  icon: {
    width: 26,
    height: 26,
  },
});

const EventStack = StackNavigator({
    EventList: {
        screen: AplEvents,
          navigationOptions: {
            title: "APL Event Listing",
          }
    },
    Details: {
        screen: EventDetails,
    },
  TabsNav: { screen: MyHomeScreen}
  });

const TabsNav = TabNavigator({
  Home: {
    screen: MyHomeScreen,
        navigationOptions: {
            tabBarLabel: 'Home',
                 tabBarIcon: ({ tintColor }) => (
                <Image
                    source={{uri: 'https://upload.wikimedia.org/wikipedia/de/thumb/9/9f/Twitter_bird_logo_2012.svg/154px-Twitter_bird_logo_2012.svg.png'}}
                    style={[styles.icon, {tintColor: tintColor}]}
                />
                ),
        },
  },
  EventList: {
    screen: EventStack,
            navigationOptions: {
            tabBarLabel: 'Events',
                 tabBarIcon: ({ tintColor }) => (
                <Image
                    source={{uri: 'https://upload.wikimedia.org/wikipedia/de/thumb/9/9f/Twitter_bird_logo_2012.svg/154px-Twitter_bird_logo_2012.svg.png'}}
                    style={[styles.icon, {tintColor: tintColor}]}
                />
                ),
        },
  },
}, {
  tabBarOptions: {
    activeTintColor: '#e91e63',
  },
});

3 个答案:

答案 0 :(得分:1)

有很多关于此问题的讨论来自本地问题3144861335,最后我们有办法解决这个问题,在2017年9月27日之后,导航版v1.0.0-beta.13

  

新功能

     

接受tabBarOnPress参数(#1335) - @cooperka

所以我们走了,

用法:

const MyTabs = TabNavigator({
  ...
}, {
  tabBarComponent: TabBarBottom /* or TabBarTop */,
  tabBarPosition: 'bottom' /* or 'top' */,
  navigationOptions: ({ navigation }) => ({
    tabBarOnPress: (scene, jumpToIndex) => {
      console.log('onPress:', scene.route);
      jumpToIndex(scene.index);
    },
  }),
});

答案 1 :(得分:1)

我无法让这个工作,并且在检查了React Navigation文档之后发现了这一点,这似乎表明后来的版本(我使用的是1.0.0-beta.27)已经改变了单个对象的方法签名:

  

tabBarOnPress回调以处理点击事件;参数是一个对象   含有:

     

previousScene:{route,index}这是我们要离开的场景

     

场景:被点击的{route,index}

     

jumpToIndex方法   可以为你执行导航

https://reactnavigation.org/docs/en/tab-navigator.html#tabbaronpress

考虑到这一点,以及来自beausmith here的代码,我把它放在一起。

navigationOptions: ({ navigation }) => ({
    tabBarOnPress: (args) => {
        if (args.scene.focused) { // if tab currently focused tab
        if (args.scene.route.index !== 0) { // if not on first screen of the StackNavigator in focused tab.
            navigation.dispatch(NavigationActions.reset({
            index: 0,
            actions: [
                NavigationActions.navigate({ routeName: args.scene.route.routes[0].routeName }) // go to first screen of the StackNavigator
            ]
            }))
        }
        } else {
            args.jumpToIndex(args.scene.index) // go to another tab (the default behavior)
        }
    }
})

请注意,您需要从react-navigation导入NavigationActions才能使其正常工作。

希望这有助于某人:)

答案 2 :(得分:0)

查看此链接。我的问题要解决了。

<Tabs.Navigator
    initialRouteName="Home"
    tabBar={(props) => (
       <TabBar {...props} />
    )}>
    <Tabs.Screen
      name="Home"
      component={HomeView}
      options={{ unmountOnBlur: true }}
      listeners={({ navigation }) => ({
        blur: () => navigation.setParams({ screen: undefined }),
      })}
    />
  </Tabs.Navigator>

https://github.com/react-navigation/react-navigation/issues/6915#issuecomment-692761324