ReactNative导入原生模块报错TypeError: null is not an object (evaluating '_ToastExample.default.show')

本文介绍了一位开发者在React Native项目中集成自定义Toast组件时遇到的问题及解决方案。主要问题在于自定义ReactActivity未正确链接本地module,通过调整继承类并正确配置MainApplication解决了红屏错误。
部署运行你感兴趣的模型镜像

刚开始接触RN,一步一踩坑,按照RN中文网集成,到toast这里就进行不下去了,红屏报错TypeError: null is not an object (evaluating '_ToastExample.default.show')

错误原因:继承了自定义的ReactActivity,没有link到本地module

解决办法:继承

com.facebook.react.ReactActivity

这个是facebook写好的

整体代码如下

package com.yangfan.myreactnativeapp

import com.facebook.react.ReactActivity
import com.facebook.react.ReactActivityDelegate
import com.facebook.react.ReactRootView
import com.swmansion.gesturehandler.react.RNGestureHandlerEnabledRootView

class MyReactActivity : ReactActivity() {
    override fun getMainComponentName(): String? = "MyReactNativeApp"

    override fun createReactActivityDelegate(): ReactActivityDelegate {
        return object : ReactActivityDelegate(this@MyReactActivity, mainComponentName) {
            override fun createRootView(): ReactRootView = RNGestureHandlerEnabledRootView(this@MyReactActivity)
        }
    }
}

MainApplication

package com.yangfan.myreactnativeapp

import android.app.Application
import com.facebook.react.ReactApplication
import com.facebook.react.ReactNativeHost
import com.facebook.react.ReactPackage
import com.facebook.react.shell.MainReactPackage
import com.facebook.soloader.SoLoader
import com.swmansion.gesturehandler.react.RNGestureHandlerPackage


/**
 * Created by yangfan
 * nrainyseason@163.com
 */
class MainApplication : Application(), ReactApplication {


    private val mReactNativeHost = object : ReactNativeHost(this) {

        override fun getPackages(): MutableList<ReactPackage> {
            return mutableListOf(
                MainReactPackage(),
                RNGestureHandlerPackage(),
                CustomToastPackage()
            )
        }

        override fun getUseDeveloperSupport(): Boolean {
            return BuildConfig.DEBUG
        }

        override fun getJSMainModuleName(): String = "index"
    }

    override fun getReactNativeHost(): ReactNativeHost = mReactNativeHost

    override fun onCreate() {
        super.onCreate()
        SoLoader.init(this, false)
    }

}
CustomToastPackage
package com.yangfan.myreactnativeapp

/**
 * Created by yangfan
 * nrainyseason@163.com
 */


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.*

class CustomToastPackage : ReactPackage {

    override fun createViewManagers(reactContext: ReactApplicationContext): List<ViewManager<*, *>> {
        return emptyList()
    }

    override fun createNativeModules(
        reactContext: ReactApplicationContext
    ): List<NativeModule> {
        val modules = ArrayList<NativeModule>()

        modules.add(ToastModule(reactContext))

        return modules
    }

}
ToastModule
package com.yangfan.myreactnativeapp

import android.widget.Toast
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReactContextBaseJavaModule
import com.facebook.react.bridge.ReactMethod





/**
 * Created by yangfan
 * nrainyseason@163.com
 */
class ToastModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) {
    override fun getName(): String {
        return "ToastExample"
    }


    companion object {

        private val DURATION_SHORT_KEY = "SHORT"
        private val DURATION_LONG_KEY = "LONG"
    }

    override fun getConstants(): Map<String, Any>? {
        val constants = hashMapOf<String, Any>()
        constants.put(DURATION_SHORT_KEY, Toast.LENGTH_SHORT)
        constants.put(DURATION_LONG_KEY, Toast.LENGTH_LONG)
        return constants
    }

    @ReactMethod
    fun show(message:   String, duration: Int) {
        Toast.makeText(reactApplicationContext, message, duration).show()
    }
}

ToastExample.js

// ToastExample.js
/**
 * This exposes the native ToastExample module as a JS module. This has a
 * function 'show' which takes the following parameters:
 *
 * 1. String message: A string with the text to toast
 * 2. int duration: The duration of the toast. May be ToastExample.SHORT or
 *    ToastExample.LONG
 */
import { NativeModules } from "react-native";
// 下一句中的ToastExample即对应上文
// public String getName()中返回的字符串
module.exports = NativeModules.ToastExample;

调用

import ToastExample from "../toast/ToastExample";


ToastExample.show(item.content, ToastExample.SHORT)

 

您可能感兴趣的与本文相关的镜像

ACE-Step

ACE-Step

音乐合成
ACE-Step

ACE-Step是由中国团队阶跃星辰(StepFun)与ACE Studio联手打造的开源音乐生成模型。 它拥有3.5B参数量,支持快速高质量生成、强可控性和易于拓展的特点。 最厉害的是,它可以生成多种语言的歌曲,包括但不限于中文、英文、日文等19种语言

你遇到的错误: ``` TypeError: undefined is not an object (evaluating '_reactNativeThermalReceiptPrinter.default.BLEPrinter') ``` 这个错误的核心是: > 你尝试从模块 `'react-native-thermal-receipt-printer'` 的 **默认导出对象(`.default`)** 中访问 `BLEPrinter`,但这个模块 **并没有默认导出一个对象**,或者它根本没有默认导出。 --- ## 🔍 错误原因详解 ### 常见错误写法: ```js import ThermalPrinter from 'react-native-thermal-receipt-printer'; const { BLEPrinter } = ThermalPrinter; ``` 这段代码假设了模块是这样导出的: ```js export default { BLEPrinter, NetPrinter, USBPrinter } ``` 但实际上: -模块可能 **没有默认导出(no default export)** - 或者默认导出的对象中 **不包含 `BLEPrinter`** - 或者它使用的是 **具名导出(named exports)** --- ## ✅ 正确导入方式(根据模块实际结构) ### ✅ 方法 1:使用具名导入(推荐) 如果你使用的 `react-native-thermal-receipt-printer` 是 **具名导出** 的版本(大多数是这种情况),请这样导入: ```js import { BLEPrinter } from 'react-native-thermal-receipt-printer'; ``` 这样可以直接拿到 `BLEPrinter`。 --- ### ✅ 方法 2:打印模块结构确认导出内容 如果你不确定模块结构,可以这样做: ```js import * as ThermalPrinter from 'react-native-thermal-receipt-printer'; console.log('ThermalPrinter module:', ThermalPrinter); ``` 查看输出内容中是否有 `BLEPrinter`,以及它的导出方式。 --- ## ✅ 完整修复示例 ### ✅ 正确使用方式如下: ```js import { BLEPrinter } from 'react-native-thermal-receipt-printer'; const printReceipt = async () => { try { await BLEPrinter.init(); const devices = await BLEPrinter.getDeviceList(); console.log('蓝牙设备列表:', devices); if (devices.length > 0) { const printer = devices[0]; await BLEPrinter.connectPrinter(printer.address); await BLEPrinter.printText('Hello, BLE Printer!\n'); await BLEPrinter.closeConn(); } else { console.log('未找到蓝牙打印机'); } } catch (e) { console.error('打印失败:', e); } }; ``` --- ## 🧪 常见错误对比表 | 错误代码 | 正确代码 | 说明 | |----------|----------|------| | `import ThermalPrinter from ...; const { BLEPrinter } = ThermalPrinter;` | `import { BLEPrinter } from ...` | 模块不是默认导出 | | `import * as ThermalPrinter from ...; const { BLEPrinter } = ThermalPrinter;` | ✅ 有效(如果模块是具名导出) | 推荐调试时使用 | | `import ThermalPrinter from ...; ThermalPrinter.BLEPrinter` | ❌ 报错 | `ThermalPrinter` 是 `undefined` 或不是对象 | --- ## ✅ 小结 | 问题 | 原因 | 解决方法 | |------|------|----------| | `TypeError: undefined is not an object (evaluating '_reactNativeThermalReceiptPrinter.default.BLEPrinter')` | 模块没有默认导出或默认导出对象中无 `BLEPrinter` | 使用 `import { BLEPrinter } from '...'` | --- ## ✅ 补充建议 - 如果你使用的是 **商米(Sunmi)设备**,建议使用专用库 `react-native-sunmi-inner-printer`。 - 否则请使用 `react-native-thermal-receipt-printer` 并注意其导出方式。 - 建议使用 `console.log(require('react-native-thermal-receipt-printer'))` 或 `import * as ...` 来查看模块结构。 ---
评论 5
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值