作为反应导航5中的参数的传递函数

问题描述 投票:0回答:1

NOTE:此查询用于react-navigation5。

在React Navigation 4中,我们可以在导航时传递一个函数作为参数,但是在React Navigation 5中,它会发出有关序列化参数的警告。

[基本上,我想做的是,从父屏幕导航到子屏幕,获取新值并更新父屏幕的状态。

以下是我当前的实现方式:

父屏幕

_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
    });
};
reactjs react-native react-navigation
1个回答
0
投票

代替在参数中传递onSelect功能,您可以使用navigate将数据传递回前一屏幕:

// `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中处理此问题:]]

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

    this._onSelectCountry(result);
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.