【问题标题】:ReactNative - unable to call function from native moduleReactNative - 无法从本机模块调用函数
【发布时间】:2016-03-17 15:36:04
【问题描述】:

我有现有的 ReactNative 项目。

现在我正在尝试连接到一些本机库。我一直在通过官方Native modules guide

在我的代码中,我添加了包含此代码的 CalendarManager.h 文件:

#import <Foundation/Foundation.h>
#import "RCTBridgeModule.h"

@interface CalendarManager : NSObject <RCTBridgeModule>

@end

我也有 CalendarManager.m 文件:

#import "CalendarManager.h"

@implementation CalendarManager

RCT_EXPORT_MODULE();

RCT_EXPORT_METHOD(addEvent:(NSString *)name location:(NSString*)location)
{
   //RCTLogInfo(@"Pretending to create an event %@ at %@", name, location);
}

@end

此文件通过 XCode 添加到与 AppDelegate.m 文件相同的级别。

在我的 javascript 代码中,我这样做:

import React from 'react-native';

然后我像这样调用该函数:

var cmanager = React.CalendarManager;
cmanager.addEvent('Birthday Party', '4 Privet Drive, Surrey');

我能够构建项目,但是当我在模拟器中运行它时(包管理器启动后),我得到了令人讨厌的红色错误:

Cannot read property 'addEvent' of undefined. 

在我看来,我错过了一些东西,但我不确定是什么?

【问题讨论】:

    标签: javascript ios objective-c react-native


    【解决方案1】:

    您需要使用NativeModules 来访问您的自定义原生组件。

    试试这个:

    import { NativeModules } from 'react-native';
    var CalendarManager = NativeModules.CalendarManager;
    CalendarManager.addEvent('Birthday Party', '4 Privet Drive, Surrey');
    

    【讨论】:

    • 当然。我错过了一些明显的东西。谢谢!
    • 它的工作原理感谢您的解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-31
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 2016-07-30
    • 2018-02-20
    • 1970-01-01
    相关资源
    最近更新 更多