我正在开发一个 React Native 应用程序并尝试从 android 访问 Native Module。我正在关注这个官方文档 在此处输入链接描述
创建本机模块后,当我尝试在 javaScript 类中访问它时,它显示错误“typeError: null is not an object (Evaluating _ToastExample.default.show)”
ToastModule.java
package com.awesomeproject;
import android.widget.Toast;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import java.util.Map;
import java.util.HashMap;
public class ToastModule extends ReactContextBaseJavaModule {
private static ReactApplicationContext reactContext;
private static final String DURATION_SHORT_KEY = "SHORT";
private static final String DURATION_LONG_KEY = "LONG";
ToastModule(ReactApplicationContext context) {
super(context);
reactContext = context;
}
@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();
}
}
CustomToastPackage.java
package com.awesomeproject;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class CustomToastPackage implements 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;
}
}
在 MainApplication.java 中插入了这个片段
protected List<ReactPackage> getPackages() {
@SuppressWarnings("UnnecessaryLocalVariable")
List<ReactPackage> packages = new PackageList(this).getPackages();
// Packages that cannot be autolinked yet can be added manually here, for example:
// packages.add(new MyReactNativePackage());
packages.add(new CustomToastPackage()); // <-- Add this line with your package name.
return packages;
}
ToastExample.js
import {NativeModules} from 'react-native';
module.exports = NativeModules.ToastExample;
App.js 这里我只是想从 Android Native Module 调用那个简单的 Toast 函数。
import React, { Component } from 'react';
import EmojiDict from './components/EmojiDict';
import ToastExample from './ToastExample';
export default class App extends Component {
componentDidMount(){
ToastExample.show('Awesome', ToastExample.SHORT);
}
render() {
return <
EmojiDict />;
}
}
我是 ReactNative 的新手,所以请帮我解决这个问题。提前致谢。