流程
Native端
- 创建类A继承
ReactContextBaseJavaModule
,并自定义JS需要调用的方法,主要需要加上@ReactMethod
注解; - 创建类B实现
ReactPackage
接口,并实现其createNativeModules
方法; - 在包含React的
Activity
页面上使用ReactInstanceManager.builder()
添加刚才实现的ReactPackage
。
React端
- 创建A.js文件,导入
NativeModules
,并通过实现Android端A类的getName
方法返回的字符串导出; - 在需要调用的位置引入模块,执行调用。
Native代码
ToastModule.java
public class ToastModule extends ReactContextBaseJavaModule {
private static final String DURATION_SHORT_KEY = "SHORT";
private static final String DURATION_LONG_KEY = "LONG";
public ToastModule(ReactApplicationContext reactContext) {
super(reactContext);
}
@Override
public String getName() {
return "ToastExample";
}
@Nullable
@Override
public Map<String, Object> getConstants() {
final Map<String, Object> constants = new HashMap<>();
constants.put(DURATION_SHORT_KEY, Toast.LENGTH_SHORT);
constants.put(DURATION_LONG_KEY, Toast.LENGTH_LONG);
return constants;
}
@ReactMethod
public void show(String message, int duration) {
Toast.makeText(getReactApplicationContext(), message, duration).show();
}
@ReactMethod
public void getData(String text, Callback callback) {
callback.invoke("test", text);
}
}
ToastReactPackage.java
public class ToastReactPackage implements ReactPackage {
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
List<NativeModule> modules = new ArrayList<>();
modules.add(new ToastModule(reactContext));
return modules;
}
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
}
Activity.java
// MainReactPackage必须添加
mReactInstanceManager = ReactInstanceManager.builder()
.setApplication(getApplication())
.setBundleAssetName("index.android.bundle")
.setJSMainModulePath("index")
.addPackage(new MainReactPackage())
.addPackage(new ToastReactPackage())
.setUseDeveloperSupport(BuildConfig.DEBUG)
.setInitialLifecycleState(LifecycleState.RESUMED)
.build();
React代码
ToastAn.js
import {NativeModules} from 'react-native';
module.exports = NativeModules.ToastExample;
UI.js
_toast() {
ToastExample.getData("显示吐司内容", (arg1, arg2) => {
ToastExample.show(arg1 + arg2, ToastExample.SHORT);
});
}