咱們在使用RN的時候,會發現RN提供了不少Module供JS調用,這些Module可以知足咱們一些基礎的應用場景,可是在實際的項目中,一定會有一些交互邏輯須要咱們本身去實現,這時候就須要咱們自定義一些Module供JS調用,那麼怎麼才能讓JS調用到咱們自定義的Module呢? 下面咱們就一步步的去實現JS對自定義Module的調用。java
public class ReactUiModule extends ReactContextBaseJavaModule {
public ReactUiModule(ReactApplicationContext reactContext) {
super(reactContext);
}
@Override
public String getName() {
return "ReactUiModule";
}
//toast
@ReactMethod
public void showToast(String msg) {
Toast.makeText(getReactApplicationContext(), msg, Toast.LENGTH_LONG);
}
}
複製代碼
public class MyReactPackage implements ReactPackage {
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
List<NativeModule> nativeModules = new ArrayList<>();
/*在這裏加入開發的接口*/
nativeModules.add(new ReactUiModule(reactContext));
return nativeModules;
}
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
}
複製代碼
public class MainApplication extends Application implements ReactApplication {
private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
@Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(),
new MyReactPackage()
);
}
@Override
protected String getJSMainModuleName() {
return "index";
}
};
@Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
@Override
public void onCreate() {
super.onCreate();
SoLoader.init(this, /* native exopackage */ false);
}
}
複製代碼
import React, {Component} from 'react';
import {Platform, StyleSheet, NativeModules, Text, View} from 'react-native';
RCTDemoToast = NativeModules.ReactUiModule; // 獲取到Native Module
type Props = {};
export default class App extends Component<Props> {
render() {
RCTDemoToast.showToast('ReactNative');
console.log('ReactNative','js first page render');
return (
<View style={styles.container}> <Text style={styles.welcome}>Welcome to React Native!</Text> <Text style={styles.instructions}>To get started, edit App.js</Text> </View>
);
}
}
複製代碼
原文連接: tech.meicai.cn/detail/72, 也可微信搜索小程序「美菜產品技術團隊」,乾貨滿滿且每週更新,想學習技術的你不要錯過哦。react