首页 > 解决方案 > 每当我尝试调用我在另一个反应本机应用程序中创建的 ReactNativeLibrary 时,我都会得到“未定义不是对象”

问题描述

我正在按照这篇文章创建一个使用命令的反应原生库npm install -g react-native-create-library。我的库非常简单,它所做的只是弹出一个警报,并且只有下面给出的索引文件中的代码:

import { NativeModules } from 'react-native';

const { RNReactNativeOgonModule } = NativeModules;

class RNReactNativeOgon {
    create() {
        Alert.alert('You need to...')
    }
}

export default new RNReactNativeOgon()

然后我尝试通过使用以下方式打包库来将此库添加到 react-native 项目中:npm pack

然后我在 react-native 应用程序中安装上面创建的包,比如

npm install C:\Users\Java\Documents\CodeHub\ReactNative\ReactNativeOgon\react-native-react-native-ogon-1.0.0.tgz

然后我将它导入到我想使用它的文件中,如下所示:

import React, {Component} from 'react';
import {Platform, Alert, StyleSheet, Text, TouchableOpacity, View} from 'react-native';
import {RNReactNativeOgon} from 'react-native-react-native-ogon';

const instructions = Platform.select({
  ios: 'Press Cmd+R to reload,\n' + 'Cmd+D or shake for dev menu',
  android:
    'Double tap R on your keyboard to reload,\n' +
    'Shake or press menu button for dev menu',
});

type Props = {};
export default class App extends Component<Props> {
  render() {

    const showAlert = () =>{
      RNReactNativeOgon.create();
   }
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>Welcome to React Native</Text>
        <Text style={styles.instructions}>To get started, edit App.js</Text>
        <Text style={styles.instructions}>{instructions}</Text>
        <TouchableOpacity onPress ={showAlert} style = {styles.button}>
         <Text>Alert</Text>
        </TouchableOpacity>
      </View>
    );
  }
}

我得到错误

> undefined is not an object (evaluating 'new_reactNativeReactNativeOgon.RNReactNativeOgon.create)

每当我单击触发该功能的 TouchableOpcaity 小部件时:

const showAlert = () =>{ 
new RNReactNativeOgon.create();
}

含义import {RNReactNativeOgon} from 'react-native-react-native-ogon';返回一个未定义的对象。

请问,我做错了什么?

标签: react-native

解决方案


你有没有尝试过 :

import RNReactNativeOgon from 'react-native-react-native-ogon';

由于您的库具有默认导出,因此您必须在没有花括号的情况下导入它{ }


推荐阅读