...

반응형

리액트 네이티브 안드로이드 소스 모듈화 방법

일단 아래의 사이트에 자세히 나와 있지만 저는 따라해서 많이 헤맸네요

https://reactnative.dev/docs/native-modules-android

위의 사이트에도 나와있는 리액트 네이티브에서 안드로이드의 Toast 기능을 모듈화 해서 사용해 보겠습니다

먼저 android - app - main - java - 자신의 프로젝트 - 아래에 ToastModule.java 파일을 만들고 아래의 코드를 입력합니다(앞으로 프로젝트 이름은 com.sinwho로 하겠습니다)

 

---------- ToastModule.java ----------
package com.sinwho;

import android.widget.Toast;

import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;

import java.util.Map;
import java.util.HashMap;

import android.util.Log;

public class ToastModule extends ReactContextBaseJavaModule {
    private static ReactApplicationContext reactContext;

    private static final String DURATION_SHORT_KEY = "SHORT";
    private static final String DURATION_LONG_KEY = "LONG";

    ToastModule(ReactApplicationContext context) {
        super(context);
        reactContext = context;
    }


    @Override
    public String getName() {
        return "sinwho";
    }


    @ReactMethod
    public String show(String message) {

        Toast.makeText(getReactApplicationContext(), message, 10).show();
    }
  
}

 

위의 코드에서 getName은 나중에 호출할 모듈의 이름입니다
show() 함수는 리액트 네이티브에서 사용할 함수로 @ReactMethod를 함수 위에 적어줍니다

같은 위치에 ToastManager.java 파일을 만들고 아래의 코드를 입력합니다

 

---------- ToastManager.java ----------

package com.sinwho;

import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ToastManager implements ReactPackage {

  @Override
  public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
    return Collections.emptyList();
  }

  @Override
  public List<NativeModule> createNativeModules(
                              ReactApplicationContext reactContext) {
    List<NativeModule> modules = new ArrayList<>();

    modules.add(new ToastModule(reactContext));

    return modules;
  }


   // Backward compatibility
   public List<Class<? extends JavaScriptModule>> createJSModules() {
       return new ArrayList<>();
   }
}

 

위에서 만든 모듈을 modules.add(new ToastModule(reactContext))와 같이 등록합니다

같은 위치에 MainApplication.java 파일의 protected List<ReactPackage> getPackages() 함수에

packages.add(new ToastManager()); 을 추가합니다

이제 리액트 네이티브의 소스 파일에서 아래 구문을 추가 하고 사용하시면 됩니다

import { NativeModules } from 'react-native';

사용하실때는 
NativeModules.sinwho.show("Toast Test");
와 같이 사용하시면 됩니다 
여기서 sinwho는 모듈의 getName()에서 반환해주는 값을 적어주시면 됩니다

반응형