自定义本机模块在升级以响应本机0.61后停止在android上工作

时间:2019-11-03 16:28:47

标签: android react-native

我将本机反应从0.59.9升级到0.61.2, 从那时起,我无法在android上使用我的自定义本机模块。

试图在react native(https://facebook.github.io/react-native/docs/native-modules-android)中使用指南中的代码,以查看新版本的RN是否有所更改,但我不断获得

   TypeError: Cannot read property 'show' of undefined.

这是我代码的基础:

ToastModule.java

        public class ToastModule extends ReactContextBaseJavaModule {

        ...

        @Override
        public String getName() {
            return "ToastExample";
        }

        @ReactMethod
        public void show(String message, int duration) {
            Toast.makeText(getReactApplicationContext(), message, duration).show();
        }

        }

CustomToastPackage.java

        public class CustomToastPackage implements ReactPackage {
        ...
            @Override
            public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
                return Arrays.<NativeModule>asList(new ToastModule(reactContext));
            }

        }

MainApplication.java

        ...

        import com.xxx.CustomToastPackage;

        public class MainApplication extends NavigationApplication {

        ...

            @Nullable
            @Override
            public List<ReactPackage> createAdditionalReactPackages() {
                return new PackageList(this).getPackages();
            }

            protected List<ReactPackage> getPackages() {
                List<ReactPackage> packages = new ArrayList<>();
                packages.add(new IntercomPackage());
                packages.add(new CustomToastPackage());
                return packages;
            }


        }

example.js

        import {NativeModules} from 'react-native';
        NativeModules.ToastExample.show("test", NativeModules.ToastExample.DURATION_SHORT_KEY)

当尝试在JS中进行调试时,我看到从react-native导出的NativeModules对象确实没有所需的模块。

使本机模块正常工作对我来说至关重要。

我想念什么?

1 个答案:

答案 0 :(得分:0)

我的问题是我的MainApplication.java文件:

我的原始代码是:

@Nullable
@Override
public List<ReactPackage> createAdditionalReactPackages() {
    // I thought this will get the packages from the protected function
    // But it did not
    return new PackageList(this).getPackages();
}

protected List<ReactPackage> getPackages() {
    List<ReactPackage> packages = new ArrayList<>();
    packages.add(new CustomToastPackage());
    packages.add(new IntercomPackage());
    return packages;
}

当我删除'getPackages'函数并更改'createAdditionalReactPackages'时,一切都按预期进行了:)

@Nullable
@Override
public List<ReactPackage> createAdditionalReactPackages() {
    List<ReactPackage> packages = new PackageList(this).getPackages();
    packages.add(new CustomToastPackage());
    return packages;
}