无法运行本机模块官方示例

时间:2019-03-19 13:50:25

标签: android react-native react-native-native-module

我遵循了文档,尝试从react native调用ToastExample.show()。 但它总是显示 error

我的代码:

公共类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();
}

}

MainApplication.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);

我已经多次尝试运行Android和./gradlew了。 代码有什么问题?

0 个答案:

没有答案