我按照文档并尝试从 react native 调用 ToastExample.show() 。但它总是显示 错误
我的代码:
公共类 CustomToastPackage 实现 ReactPackage {
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
@Override
public List<NativeModule> createNativeModules(
ReactApplicationContext reactContext) {
List<NativeModule> modules = new ArrayList<>();
modules.add(new ToastModule(reactContext));
return modules;
}
}
public class ToastModule extends ReactContextBaseJavaModule {
private static final String DURATION_SHORT_KEY = "SHORT";
private static final String DURATION_LONG_KEY = "LONG";
public ToastModule(ReactApplicationContext reactContext) {
super(reactContext);
}
@Override
public String getName() {
return "ToastExample";
}
@Override
public Map<String, Object> getConstants() {
final Map<String, Object> constants = new HashMap<>();
constants.put(DURATION_SHORT_KEY, Toast.LENGTH_SHORT);
constants.put(DURATION_LONG_KEY, Toast.LENGTH_LONG);
return constants;
}
@ReactMethod
public void show(String message, int duration) {
Toast.makeText(getReactApplicationContext(), message, duration).show();
}
}
主应用程序.Java:
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(),
new ReanimatedPackage(),
new VectorIconsPackage(),
new RNGestureHandlerPackage(),
new CustomToastPackage(),
new RNSharedPreferencesReactPackage()
);
}
ToastExample.js:
import {NativeModules} from 'react-native';
module.exports = NativeModules.ToastExample;
在我的屏幕上:
import ToastExample from './ToastExample'
ToastExample.show('Awesome', ToastExample.SHORT);
我已经尝试过 run-android 和 ./gradlew clean 很多次了。代码有什么问题?