在本机中调​​用导出的方法

时间:2016-10-14 09:20:01

标签: android ios objective-c react-native native-module

我想在Objective C中创建一个视图并在本机中使用,但不知道如何执行此操作 这是我的代码: OBJ-C:

#import "DGTAuthenticateButtonView.h"
#import "RCTBridge.h"
#import "RCTEventDispatcher.h"
#import "UIView+React.h"
#import <DigitsKit/DigitsKit.h>

@implementation DGTAuthenticateButtonView

RCT_EXPORT_MODULE()
- (UIView *) view {
  UIButton *button = [[UIButton alloc] init];
  [button setTitle:@"REGISTER" forState:UIControlStateNormal];
  return button;

}

RCT_EXPORT_METHOD(authenticate) {
  Digits *digits = [Digits sharedInstance];
  DGTAuthenticationConfiguration *configuration = [[DGTAuthenticationConfiguration alloc] initWithAccountFields:DGTAccountFieldsDefaultOptionMask];
  configuration.phoneNumber = @"+345555555555";
  [digits authenticateWithViewController:nil configuration:configuration completion:^(DGTSession *newSession, NSError *error){
  }];

}

@end

我想在TouchableOpacity中致电authenticate,但它无效:(

import React, {Component} from 'react';
import {
    AppRegistry,TouchableOpacity
} from 'react-native';



var requireNativeComponent = require('requireNativeComponent');

var DGTAuthenticateButtonView = requireNativeComponent('DGTAuthenticateButtonView', DGTAuthenticateButtonView);

class TestProj extends Component {
    render() {
        return (

            <TouchableOpacity style={{flex: 1, backgroundColor: 'green'}}
                onPress={() => DGTAuthenticateButtonView.authenticate()}
            />

        )
    }
}

AppRegistry.registerComponent('TestProj', () => TestProj);

任何人都知道如何做到这一点?提前谢谢。

1 个答案:

答案 0 :(得分:1)

这似乎是你在这里混合了两个不同的概念。

您可以创建一个Native UI Component - 一个本地视图,您可以将其用作RN render函数中的一个组件;或者你可以创建一个Native Module - 一个模块,它允许你添加本机功能并从你的JS代码中调用它,这个模块没有视图。

据我所知(您没有包含RCTViewManager子类的代码),您尝试在本机端创建Native UI Components(返回视图),但不要在你的JS中使用它(不用作render中的组件)。您还应该知道,您不能直接在原生视图上调用方法,就像您在这里尝试一样。

我建议您使用以下解决方案之一:

  1. 如果您确实需要自定义原生UI,请按照创建Native UI Component的说明进行操作,然后使用您的组件 你的渲染功能。然后,您可以使用道具传达按钮按下 映射到回调(请参阅here关于从本机到JS的事件)。
  2. 如果您不需要自定义用户界面(您希望在示例中继续使用TouchableOpacity),则可以按照说明创建Native Module。然后,您可以静态调用authenticate方法,因为您尝试在此处仅执行本机逻辑。您甚至可以修改authenticate方法以接收其他参数 - 拒绝/解决承诺或回调以在JS完成时通知JS。