在 react-navigation 5 中将函数作为参数传递 [英] Passing function as a param in react-navigation 5

查看:30
本文介绍了在 react-navigation 5 中将函数作为参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意:此查询适用于 react-navigation 5.

NOTE: This query is for react-navigation 5.

在反应导航 4 中,我们可以在导航时将函数作为参数传递,但在反应导航 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:

父屏幕

_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> 

子屏幕

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

推荐答案

不是在 params 中传递 onSelect 函数,您可以使用 navigate 将数据传递回上一屏:

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

然后,您可以在您的第一个屏幕(在 componentDidUpdateuseEffect 中)处理这个:

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

这篇关于在 react-navigation 5 中将函数作为参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆