关于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 getConstants() {
        final Map 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 createNativeModules(ReactApplicationContext reactContext) {
        List modules = new ArrayList<>() ;
        modules.add(new LogModule(reactContext)) ;
        modules.add(new ToastModules(reactContext)) ;
        return modules ;
    }
    @Override
    public List<Classextends JavaScriptModule>> createJSModules() {
        return Collections.emptyList();
    }
    @Override
    public List createViewManagers(ReactApplicationContext reactContext) {
        return Collections.emptyList();
    }
}

3、在MainActivity.java里注册AppReactPackage:

 @Override
    protected List getPackages() {
        return Arrays.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。

问题参考:https://github.com/facebook/react-native/issues/3685

你可能感兴趣的:(React,Native)