1. 程式人生 > >關於React-native裡Android原生模組和元件的寫法

關於React-native裡Android原生模組和元件的寫法

原生模組就是把Android裡的API匯出來給JS呼叫,說簡單一點,就是讓自己寫的Java函式能夠在React Native的js程式碼裡呼叫。比如一些實現高效能的、多執行緒的程式碼,還有譬如圖片處理、資料庫、或者各種高階擴充套件等等。
舉個栗子:
Toast模組:
1、繼承ReactContextBaseJavaModule類,實現安卓裡面的Toast功能(就是呼叫Toast.makeText(*)),程式碼如下:

public class ToastModules extends ReactContextBaseJavaModule {
    private static final
String MODULES_NAME_TOAST = "ToastAndroid1" ; private static final String TOAST_LONG_KEY = "LONG" ; private static final String TOAST_SHORT_KEY = "SHORT" ; public ToastModules(ReactApplicationContext reactContext) { super(reactContext); } @Nullable @Override public
Map<String, Object> getConstants() { final Map<String, Object> constants = new HashMap<>() ; constants.put(TOAST_LONG_KEY, Toast.LENGTH_LONG) ; constants.put(TOAST_SHORT_KEY, Toast.LENGTH_SHORT) ; return constants; } @Override public String getName
() { return MODULES_NAME_TOAST; } @ReactMethod public void show(String txt , int duration) { Toast.makeText(getReactApplicationContext(),txt,duration).show() ; } }

2、建立類實現ReactPackage:

public class AppReactPackage implements ReactPackage {
    @Override
    public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
        List<NativeModule> modules = new ArrayList<>() ;
        modules.add(new LogModule(reactContext)) ;
        modules.add(new ToastModules(reactContext)) ;
        return modules ;
    }
    @Override
    public List<Class<? extends JavaScriptModule>> createJSModules() {
        return Collections.emptyList();
    }
    @Override
    public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
        return Collections.emptyList();
    }
}

3、在MainActivity.java裡註冊AppReactPackage:

 @Override
    protected List<ReactPackage> getPackages() {
        return Arrays.<ReactPackage>asList(
            new MainReactPackage(),new AppRactPackages();
        );
    }

錯誤統計:

Running application with appParams: {"initialProps":{},"rootTag":1}.
__DEV__ === true, development-level warning are ON, performance optimizations are OFF

解決方法:在AS裡clean一下project,然後gradle,然後start package,run-android。