第一步首先创建ReactNative 模块类继承ReactContextBaseJavaModule
import android.widget.Toast;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
/**
- Created by Administrator on 2016/9/22.
*/
public class MyNativeModule extends ReactContextBaseJavaModule {
public static final String REACTCLASSNAME = "MyNativeModule";
private Context mContext;
public MyNativeModule(ReactApplicationContext reactContext) {
super(reactContext);
mContext = reactContext;
}
@Override
public String getName() {
return REACTCLASSNAME;
}
/**
第二步创建一个React包管理器实现ReactPackage将每个模块放到模块集合中
import com.facebook.react.bridge.JavaScriptModule;
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;
/**
- Created by Administrator on 2016/9/22.
*/
public class MyReactPackage implements ReactPackage {
@Override
public List
List
modules.add(new MyNativeModule(reactContext));
return modules;
}
@Override
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}
@Override
public List
return Collections.emptyList();
}
}
第三步在应用入口注册这个React包管理器
import android.util.Log;
import com.facebook.react.ReactApplication;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import java.util.Arrays;
import java.util.List;
public class MainApplication extends Application implements ReactApplication {
private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
@Override
protected boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(),//在应用中<a href="https://www.jb51.cc/tag/zhuce/" target="_blank" class="keywords">注册</a>这个包管理器
new MyReactPackage()
);
}
};
@Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
}
第四步就是在ReactNative中调用react-native中提供一个NativeModules通过模块名字和方法名字进行调用
import {
AppRegistry,StyleSheet,Text,View,NativeModules,} from 'react-native';
class Mixture extends Component {
render() {
return (
/**
- 调用原生方法
*/
onClick() {
NativeModules.MyNativeModule.callNativeMethod('成功调用原生方法');
}
}
const styles = StyleSheet.create({
container: {
flex: 1,justifyContent: 'center',alignItems: 'center',backgroundColor: '#F5FCFF',},instructions: {
textAlign: 'center',color: '#333333',marginBottom: 5,});
AppRegistry.registerComponent('Mixture',() => Mixture);
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
原文链接:https://www.f2er.com/js/45375.html