简体   繁体   中英

Unable to set a function as param using setParams in react-navigation

I'm trying to set scroll to top function in a screen which contains ListView when already focused tab is clicked.

I'm using react-navigation 2.0.0 and react-native 0.59.8 Here is how my navigator looks like:

FeedScreen.js returns
   render() {
    return <Nodes {...this.props} />;
  }

Nodes.js
   callScrollToTop = () => {
     this.listView.scrollToOffset({ offset: 0, animated: true });
   }
   componentDidMount(){
     this.props.navigation.setParams({
        scrollToTop: this.callScrollToTop
     })
   }
   // Here, I am able to set a string param like name: "Alice" and that can be seen in navigation state on TabBarOnPress 

const Feed = createStackNavigator({
  Feed: {
    screen: FeedScreen
  }
});

const Profile = createStackNavigator({
  Profile: {
    screen: ProfileScreen
  }
});

 const TabsScreens = createBottomTabNavigator(
  {
    Feed,
    Profile
  },
  {
    navigationOptions: ({ navigation }) => ({
    tabBarOnPress: ({ navigation }) => {
        if (
          navigation.isFocused() &&
          navigation.state.params &&
          navigation.state.params.scrollToTop
        ) {
          navigation.state.params.scrollToTop();
        }
   })
  })

I don't want an exact solution like scrolling list view to top. Ability to set a function as param on componentDidMount and access it on tabBarOnPress is enough. Please help me find a solution to this.

Thanks!!

In your respective tab component use these,

import { NavigationEvents } from 'react-navigation';

render() {
   return (
    <View>
    <NavigationEvents
       onWillFocus={(route) => {
         if (route.action.routeName === /* check the screen name mentioned in the routes */) {
           //call the function u need
         }
       }}
     />
    // add other components as usual
    </View>
   );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM