在使用RN開發過程中,難免有些原生功能需要要自己來實現,下面總結一下在使用RN與原生開發交互。
1、在原生代碼中定義實現類
1.1 首先繼承 ReactContextBaseJaveModule抽象類
public class SomeModule extends ReactContextBaseJavaModule{}
1.2 實現構造方法
public SomeModule(ReactApplicationContext context){
super(context);
}
1.3 實現 getName() 方法,並返回一個字符串
@Override
public String getName(){
return "SomeModule"; //返回值將在RN代碼中使用
}
1.4 實現功能方法,使用注解@ReactMethod修飾(使用修飾ReactMethod的方法,可以在RN中被調用)
@ReactMethod
public void callbackMethod(Object paramsFromJS,Callback ok,Callback error){
//... do something , result = true
if(result){
ok.invoke("params");
}else{
error.invoke("error");
}
}
@ReactMethod
public void promiseMethod(Object paramsFromJS,Promise promise){
// ... do something, result = true
if(result){
promise.resolve("params");
}else{
promise.reject("error");
}
}
2、原生注冊模塊
2.1 注冊模塊
實現ReactPackage接口
public class SomeReactPackage implements ReactPackage{
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext){
return Collections.<NativeModule>singletonList(new SomeModule(reactContext));
}
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}
}
2.2 添加模塊
在MainPackage類的getPackages()方法中添加模塊
public List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(new MainReactPackage(),new SomeReactPackage());
}
3、RN中JS代碼
3.1 首先導入庫
import { NativeModules } from 'react-native'
3.2 調用原生方法
3.2.1回調方法
NativeModules.SomeModule.callbackMethod('params',(ok)=>{},(error)=>{});
3.2.2 Promise方法
NativeModules.SomeModule.promiseMethod('params').then((ok)=>{}).catch((error)=>{});
3.2.3 說明
NativeModules : 不用解釋,react-native提供的類庫
SomeModule : 原生代碼中,getName()方法返回字符串
callbackMethod() / promiseMethod() : 原生代碼中,使用@ReactMethod修飾的方法
(ok)=>{} : 成功回調方法
(error)=>{} : 失敗回調方法
至此,RN與原生混合開發最基本的流程已經OK 。