【问题标题】:React native custom UI component with Swift: how to access reactTag in event使用 Swift 反应原生自定义 UI 组件:如何在事件中访问 reactTag
【发布时间】:2015-11-03 17:10:26
【问题描述】:

在 Swift 中创建自定义 UI 组件时,如何访问 reactTag 以触发返回给 React Native 的事件?

使用以下代码在 Swift 中创建一个带有按钮的自定义组件: 单击按钮时,使用 bridge.eventDispatcher 到 sendInputEventWithName 应该会在 React Native JavaScript 代码中引发一个事件。 这是通过将 reactTag 作为事件字典的一部分传递来完成的。 但是,我不清楚如何访问 reactTag 属性,甚至不清楚它在哪里可用。

(稍微挖掘一下,它似乎出现在名为 RCTShadowView 的东西上,但是我的 shadowView 上的 reactTag 始终是 nil)

斯威夫特

//  FooView.swift
import UIKit


@objc(FooView)
class FooView: UIView {
    @objc var bridge: RCTBridge!

    required override init(frame: CGRect) {
        super.init(frame: frame)
        let button = UIButton(frame: CGRect(x: 10, y: 10, width: 244, height: 244))
        button.addTarget(self, action: "buttonClicked:", forControlEvents: .TouchUpInside)
        self.addSubview(button)
    }

    func buttonClicked(sender: AnyObject?) {
        let event = [
            "target": "", // <-- how can one get access to the reactTag property?
        ]

        self.bridge.eventDispatcher.sendInputEventWithName("topChange", body: event)
    }
}

 目标 C

//  FooViewBridge.m

#import "RCTBridgeModule.h"
#import "RCTViewManager.h"
#import "FooProj-Swift.h"


@interface RCTFooViewManager : RCTViewManager
@end


@implementation RCTFooViewManager


RCT_EXPORT_MODULE()

- (UIView *)view
{
    FooView* fooView = [[FooView alloc] init];
    fooView.bridge = self.bridge;
    fooView.shadowView = self.shadowView; // <-- was hoping this would have a reactTag but it's always nil
    return fooView;
}


@end

【问题讨论】:

  • 你知道如何获取/设置 reactTag 了吗?
  • 我没有。我最终做的是使用self.bridge.eventDispatcher.sendAppEventWithName("buttonClicked", body: ["button": "foo"])。它显然不像我们有标签那样优雅,但它至少可以识别事件并收听它。
  • @Jones 你能提供你的例子的 github repo 吗?我认为这可以帮助我

标签: react-native


【解决方案1】:

FooView.swift 需要能够看到self.reactTag,这是在UIView+React.h 中声明的。

这需要添加到项目的Bridging-Header.h。

#import "UIView+React.h"

旁注:您可能不想直接使用sendInputEventWithName,而是使用here 给出的答案的Swifty 变体

【讨论】:

  • 如果你使用的是 Objective-C 而不是 #import &lt;React/UIView+React.h&gt;
猜你喜欢
  • 2016-08-11
  • 1970-01-01
  • 1970-01-01
  • 2016-06-03
  • 1970-01-01
  • 2019-06-21
  • 2017-03-17
  • 2020-02-04
  • 2020-08-12
相关资源
最近更新 更多