public class AnExampleReactPackage implements ReactPackage {
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
@Override public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}
/**
* 在这个方法中返回自己封装的toast 这里存放的就是自己刚才创建的MyToastModule,注意这里的泛型是NativeModule
* @param reactContext
* @return
*/
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
List<NativeModule> modules = new ArrayList<>();
modules.add(new MyToastModule(reactContext));
return modules;
}
}
第3部我们需要在MainActivity的中注册我们自己定义的toastpackage
public class MainActivity extends ReactActivity {
/**
* Returns the name of the main component registered from JavaScript.
* This is used to schedule rendering of the component.
*/
@Override protected String getMainComponentName() {
return "RnDemo";
}
/**
* Returns whether dev mode should be enabled.
* This enables e.g. the dev menu.
*/
@Override protected boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
/**
* A list of packages used by the app. If the app uses additional views
* or modules besides the default ones, add more packages here.
*/
@Override protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(new MainReactPackage(),
new AnExampleReactPackage());//在这里加上我自己注册的package
}
}
最后一步我们在js端调用
/**
* Sample React Native App
* https://github.com/facebook/react-native
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
NativeModules, 需要引入这个模块
View
} from 'react-native';
var MyToastModule= NativeModules.MyToastModule;
//这里一定要调用
MyToastModule.show("封装原声Toast",MyToastModule.SHORT);
class RnDemo extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to rn show
</Text>
<Text style={styles.instructions}>
To get started, edit index.android.js
</Text>
<Text style={styles.instructions}>
Shake or press menu button for dev menu
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('RnDemo', () => RnDemo);