【问题标题】:Call exported method in react native在本机反应中调用导出的方法
【发布时间】:2017-02-23 16:02:36
【问题描述】:

我想在 Objective C 中创建一个视图并在 react native 中使用,但不知道该怎么做 这是我的代码: 对象-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);

有人知道怎么做吗?提前致谢。

【问题讨论】:

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


    【解决方案1】:

    看来您在这里混合了 2 个不同的概念。

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

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

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

    1. 如果您确实需要自定义的原生 UI - 按照创建 Native UI Component 的说明操作,然后在 你的渲染功能。然后,您可以使用道具传达按钮按下 映射到回调(请参阅here,了解从本机到 JS 的事件)。
    2. 如果您不需要自定义 UI(您想继续使用 TouchableOpacity,如您的示例中所示),您可以按照说明创建 Native Module。然后,您将能够静态调用 authenticate 方法,就像您在此处尝试执行的仅执行本机逻辑一样。你甚至可以修改authenticate 方法来接收额外的参数——一个reject/resolve promise 或者一个回调来在它完成时通知JS。

    【讨论】:

    • 我遵循第二个解决方案的 fb 示例代码,它可以工作。非常感谢:D
    猜你喜欢
    • 2022-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-15
    • 2019-02-04
    相关资源
    最近更新 更多