在react-navigation 5中将函数作为参数传递

Aya*_*yan 29 reactjs react-native react-navigation

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

在 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> 
Run Code Online (Sandbox Code Playgroud)

儿童屏幕

_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
    });
};
Run Code Online (Sandbox Code Playgroud)

sat*_*164 16

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
    }
  });
};
Run Code Online (Sandbox Code Playgroud)

然后,您可以在第一个屏幕中处理此问题(在componentDidUpdate或中useEffect):

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

    this._onSelectCountry(result);
  }
}
Run Code Online (Sandbox Code Playgroud)


Geo*_*ean 6

不建议通过 react native 导航参数传递回调,这可能会导致状态冻结(无法正确更新)。这里更好的解决方案是使用 EventEmitter,因此回调保留在 Screen1 中,并在 Screen2 发出事件时调用。

屏幕 1 代码:

import {DeviceEventEmitter} from "react-native"

DeviceEventEmitter.addListener("event.testEvent", (eventData) => 
callbackYouWantedToPass(eventData)));
Run Code Online (Sandbox Code Playgroud)

屏幕 2 代码:

import {DeviceEventEmitter} from "react-native"

DeviceEventEmitter.emit("event.testEvent", {eventData});

useEffect(() => {
return () => {
    DeviceEventEmitter.removeAllListeners("event.mapMarkerSelected")
  };
}, []);
Run Code Online (Sandbox Code Playgroud)