【发布时间】: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