我想为Android做一个React Antive模块,但我无法访问模块的方法。它引发了"未定义不是对象"的错误。我的代码怎么了?
在这种情况下,按下按钮时,我想调用foo()方法。
我的代码如下:
testmodule.java
public class TestModule extends ReactContextBaseJavaModule {
public TestModule(ReactApplicationContext reactContext) {
super(reactContext);
}
@Override
public String getName() {
return "TestModule";
}
@ReactMethod
public void foo(){
}
}
testpackage.java
public class TestPackage implements ReactPackage{
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
List<NativeModule> modules = new ArrayList<>();
modules.add(new TestModule(reactContext));
return modules;
}
@Override
public List<Class<? extends JavaScriptModule>> createJSModules() {
return null;
}
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return null;
}
}
myApplication.java
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 TestPackage(), //Added my TestPackage
new ToastPackage()
);
}
};
@Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
@Override
public void onCreate() {
super.onCreate();
SoLoader.init(this, /* native exopackage */ false);
}
}
index.android.js
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Button,
NativeModules,
} from 'react-native';
var toast = NativeModules.Toast;
var test = NativeModules.TestModule;
export default class RNModuleTest extends Component {
showToast(){
toast.show("Hello from toast", toast.LONG);
}
showTest(){
test.foo();
}
render() {
return (
<View style={styles.container}>
<Button title="Toast" onPress={this.showToast}/>
<Button title="testModule" onPress={this.showTest} />
</View>
);
}
}
我解决了它。
在testpackage.java文件上,createJSModules()
和createViewManagers()
方法应返回Collections.emptyList()
,而不是返回null
。