Passing function as a param in react-navigation 5

只谈情不闲聊 提交于 2021-01-20 23:51:54

问题


NOTE: This query is for react-navigation 5.

In react navigation 4 we could pass a function as a param while navigating but in react navigation 5, it throws a warning about serializing params.

Basically, what I am trying to do is, navigate to a child screen from parent screen, get a new value and update the state of the parent screen.

Following is the way I am currently implementing:

Parent Screen

_onSelectCountry = (data) => {
    this.setState(data);
};
.
.
.

<TouchableOpacity
    style={ styles.countrySelector }
    activeOpacity={ 0.7 }
    onPress={ () => Navigation.navigate("CountrySelect",
        {
             onSelect: this._onSelectCountry,
             countryCode: this.state.country_code,
        })
    }
>
.
.
.
</TouchableOpacity> 

Child Screen

_onPress = (country, country_code, calling_code) => {
    const { navigation, route } = this.props;
    navigation.goBack();
    route.params.onSelect({
        country_name: country,
        country_code: country_code,
        calling_code: calling_code
    });
};

回答1:


Instead of passing the onSelect function in params, you can use navigate to pass data back to the previous screen:

// `CountrySelect` screen
_onPress = (country, country_code, calling_code) => {
  const { navigation, route } = this.props;
  navigation.navigate('NameOfThePreviousScreen', {
    selection: {
      country_name: country,
      country_code: country_code,
      calling_code: calling_code
    }
  });
};

Then, you can handle this in your first screen (in componentDidUpdate or useEffect):

componentDidUpdate(prevProps) {
  if (prevProps.route.params?.selection !== this.props.route.params?.selection) {
    const result = this.props.route.params?.selection;

    this._onSelectCountry(result);
  }
}



回答2:


There is a case when you have to pass a function as a param to a screen.

For example, you have a second (independent) NavigationContainer that is rendered inside a Modal, and you have to hide (dismiss) the Modal component when you press Done inside a certain screen.

The only solution I see for the moment is to put everything inside a Context.Provider then use Context.Consumer in the screen to call the instance method hide() of Modal.



来源:https://stackoverflow.com/questions/60114496/passing-function-as-a-param-in-react-navigation-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!