封装原生模块
用androidsdd打开HelloWrold,android项目
新建HelloWorldPackage,ToastModule,WebViewManger
//HelloWorldPackage
public class HelloWorldPackage implements ReactPackage {
//这里面添加封装的模块
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
List<NativeModule> moudels = new ArrayList<>();
moudels.add(new com.helloworld.ToastModule((reactContext)));//添加ToaskModule模块
return moudels;
}
//这里面添加封装的组件
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Arrays.<ViewManager>asList(new WebViewManger());//添加WebViewManger组件
}
}
//ToastModule
//必须继承ReactContextBaseJavaModule类
public class ToastModule extends ReactContextBaseJavaModule {
//构造函数
public ToastModule(ReactApplicationContext reactContext) {
super(reactContext);
}
//必须返回模块的名字
@Override
public String getName() {
return "ToastExample";
}
//模块中定义的常量
@Nullable
@Override
public Map<String, Object> getConstants() {
final Map<String,Object> contents = new HashMap<>();
contents.put("SHORT", Toast.LENGTH_SHORT);
contents.put("LENG",Toast.LENGTH_LONG);
return contents;
}
//定义模块中的方法
@ReactMethod
public void show(String msg,int duration){
//第一个参数是RN上下文
Toast.makeText(getReactApplicationContext(), msg,duration).show();
}
}
//WebViewManger
public class WebViewManger extends SimpleViewManager<WebView> {
public static final String REACT_CLASS = "RCTWebView";
@Override
public String getName() {
return REACT_CLASS;
}
@Override
protected WebView createViewInstance(ThemedReactContext reactContext) {
WebView webView = new WebView(reactContext);
webView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
return webView;
}
@ReactProp(name = "url")
public void setUrl(WebView view, @Nullable String url) {
view.loadUrl(url);
}
@ReactProp(name = "html")
public void setHtml(WebView view, @Nullable String html) {
view.loadData(html, "text/html; charset=utf-8", "UTF-8");
}
}
//在MainApplication
//添加胶水管理器/程序包
new HelloWorldPackage()
//RN打开HelloWorld新建ToastDemo
import React, { Component } from "react";
import { StyleSheet, Text, View, Button, NativeModules } from "react-native";
//调取封装的模块
const Toast = NativeModules.ToastExample;
export default class ToastDemo extends Component {
constructor(props) {
super(props);
this.state = {};
}
press = () => {
//使用模块中的show方法
Toast.show("成功调取封装的模块", Toast.SHORT);
};
render() {
return (
<View>
<Button title="调取原生模块Toas" onPress={this.press} />
</View>
);
}
}