无法在反应导航中使用setParams将函数设置为参数

时间:2019-07-12 11:05:34

标签: javascript reactjs react-native react-navigation

当试图单击已经聚焦的选项卡时,我试图在包含ListView的屏幕上设置滚动到顶部功能。

我正在使用react-navigation 2.0.0和react-native 0.59.8 这是我的导航器的外观:

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();
        }
   })
  })

我不想要像顶部滚动列表视图那样的精确解决方案。能够在componentDidMount上将函数设置为param并在tabBarOnPress上访问它就足够了。请帮助我找到解决方案。

谢谢!

1 个答案:

答案 0 :(得分:0)

在您各自的标签组件中使用这些

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>
   );
}