[React-native] Native module 구현 참고했으면 하는 것

Darcy Daeseok YU ·2022년 5월 21일
0

react-native native module 만드는 법
https://reactnative.dev/docs/native-modules-android

튜토리얼 보고 따라치다가 화가나서 적는 글

친절한 설명은 좋은데 전체코드가 없어서 코드 예제들이 어디로 추가되어야 하는지 모르겠다.

딥빡침...

특히 Sending Events to JavaScript

sendEvent메소드에 reactContext를 파라미터로 넘겨줘야하는데

...생략
WritableMap params = Arguments.createMap();
params.putString("eventProperty", "someValue");
...생략
sendEvent(reactContext, "EventReminder", params);
...생략

뭐?? reactContext는 어디? 어디서 왔냐? 열받음.

아래는 전체 코드 예제
(android studio java 기준입니다.)

선언부를 아래와 같이 작성


public class CalendarModule extends ReactContextBaseJavaModule {

    ReactApplicationContext reactContext;

    CalendarModule(ReactApplicationContext context) {
        super(context);
        this.reactContext = context;
    }
    
    
    // 이벤트 호출 메소드에서 reactContext를 빼주고 전역 변수를 this.reactContext가져와서 사용한다.  
    
    private void sendEvent( String eventName, @Nullable WritableMap params){
        this.reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit(eventName,params);
    }
    
    //호출 메소드 : reactContext없이 이벤트명과 파람을 파라미터로 받는다. 
     @ReactMethod
    public void pop() {
        Log.d("pop" ,"pop called");
        WritableMap params = Arguments.createMap();
        params.putString("eventProperty", "someValue");
        sendEvent( "EventReminder", params);
    }
} 

위와 같이 구현하고 이제 리액트 네이티브 단에서 호출을 받을 이벤트 리스너를 구현하자.
아래는 리액트 네이티브 튜토리얼 코드이다.

import { NativeEventEmitter, NativeModules } from 'react-native';
...

 componentDidMount() {
   ...
   const eventEmitter = new NativeEventEmitter(NativeModules.ToastExample);
   this.eventListener = eventEmitter.addListener('EventReminder', (event) => {
      console.log(event.eventProperty) // "someValue"
   });
   ...
 }

 componentWillUnmount() {
   this.eventListener.remove(); //Removes the listener
 }

저와 같은 오류를 겪고 계신분들께... 지아요우 화이팅 치얼업

profile
React, React-Native https://darcyu83.netlify.app/

0개의 댓글