ReactNative-Android插件
一、编写插件
- android项目包目录下创建ToastModule.java并继承ReactContextBaseJavaModule
- 实现构造函数接收NAContext
- 重写getName方法返回模块名称
- 重写getConstants方法导出js使用常量
- 定义模块功能方法并使用@ReactMethod注解当前方法
package com.awesomeproject; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import java.util.HashMap; import java.util.Map; //1 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"; //2 public ToastModule(@NonNull ReactApplicationContext context) { super(context); reactContext = context; } //3 @NonNull @Override public String getName() { return "ToastExample"; } //4 @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; } //5 @ReactMethod public void show(String message, int duration) { Toast.makeText(getReactApplicationContext(), message, duration).show(); } }
二、注册插件
- android项目包目录下创建CustomToastPackage.java并继承ReactPackage
- 重写createNativeModules方法添加模块,以便js调用
- 在MainApplication.java的getPackages方法中添加新插件注册
package com.awesomeproject; import androidx.annotation.NonNull; import com.facebook.react.ReactPackage; 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 CustomToastPackage implements ReactPackage { @NonNull
回调使用
import com.facebook.react.bridge.Callback; Callback.invoke(a+b);
Promises
使用await调用配置了promise的方法并配以async
import com.facebook.react.bridge.Promise; promise.resolve(map); promise.reject(E_LAYOUT_ERROR, e);
js调用测试
export default class HelloWorldApp extends Component { handleClick(e) { ToastExample.show('hello app', ToastExample.SHORT); } render() { return ( <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}> <Button onPress={this.handleClick} title="Test Toast" color="#841584" accessibilityLabel="Learn more about this purple button" /> </View> ); } }