programing

반응 탐색 5에서 매개 변수로서의 통과 함수

jooyons 2023. 3. 31. 22:02
반응형

반응 탐색 5에서 매개 변수로서의 통과 함수

메모: 이 쿼리는 반응 탐색 5에 대한 것입니다.

리액트 네비게이션4에서는 네비게이션을 하는 동안 함수를 파라미터로 전달할 수 있지만 리액트 네비게이션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
    });
};

리액트 네이티브네비게이션 파라미터를 통해 콜백을 전달하는 것은 권장되지 않습니다.그 때문에, 상태가 프리즈 하는(올바르게 갱신되지 않는) 일이 있습니다.여기서 보다 좋은 해결책은 EventEmitter를 사용하는 것입니다.따라서 콜백은 Screen1에 남고 Screen2에서 이벤트가 발생할 때마다 호출됩니다.

화면 1 코드:

import {DeviceEventEmitter} from "react-native"

DeviceEventEmitter.addListener("event.testEvent", (eventData) => 
callbackYouWantedToPass(eventData)));

화면 2 코드:

import {DeviceEventEmitter} from "react-native"

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

useEffect(() => {
return () => {
    DeviceEventEmitter.removeAllListeners("event. testEvent")
  };
}, []);

통과하지 않고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
    }
  });
};

그러면 첫 화면에서 이 작업을 처리할 수 있습니다.componentDidUpdate또는useEffect):

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

    this._onSelectCountry(result);
  }
}

파라미터로서 기능을 화면에 전달해야 하는 경우가 있습니다.

예를 들어, 두 번째(독립적)가 있다고 가정합니다.NavigationContainer안에 그려지는 것Modal를 숨깁니다(삭제)해야 합니다.Modal[완료]를 누르면 컴포넌트는 특정 화면에서 [완료]를 누릅니다.

현재로선 모든 것을 안에 넣는 것만이 유일한 해결책입니다.Context.Provider그 후Context.Consumer화면에서 인스턴스 메서드를 호출합니다.hide()Modal.

언급URL : https://stackoverflow.com/questions/60114496/passing-function-as-a-param-in-react-navigation-5

반응형