I'm attempting to write a native UI component for react-native, and I'm having some trouble figuring out how the event system works. I've read through the documentation, and unfortunately it wasn't particularly helpful mostly because it is specific to obj-c with which I'm not very comfortable. Also not very comfortable with Swift, but it's the language I'm trying to learn at the moment. The code below is what I have so far, and my application loads just fine (no issues in XCode).
CustomViewManager.swift
import Foundation
@objc(CustomViewManager)
class CustomViewManager : RCTViewManager {
override func view() -> UIView! {
return CustomView();
}
}
CustomViewManagerBridge.m
#import "RCTBridgeModule.h"
#import "RCTViewManager.h"
@interface RCT_EXTERN_MODULE(CustomViewManager, RCTViewManager)
RCT_EXPORT_VIEW_PROPERTY(onPress, RCTDirectEventBlock)
RCT_EXPORT_VIEW_PROPERTY(list, NSArray)
@end
CustomView.h
#import "RCTView.h"
@interface CustomView : RCTView
@property (nonatomic, assign) NSArray *list;
@property (nonatomic, copy) RCTDirectEventBlock onPress;
@end
CustomView.swift
import Foundation
import UIKit
@objc(CustomView)
class CustomView : UIView {
var list: [CGFloat]? {
didSet {
print("set list")
}
}
override init(frame: CGRect) {
super.init(frame: frame);
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setOnPress(callback: RCTDirectEventBlock) {
print("set onPress", callback)
let dict:[NSObject:AnyObject] = [
"hello": "world",
]
callback(dict)
}
}
And then calling it from react using the code below:
<CustomView list={[1,2,3]} onPress={data => console.log('js', data)} />
This works fine to an extent. I can access the props which are passed from the swift code. I get the list, and the onPress function. However, when I call the callback the console.log is not triggered and I'm not quite sure why. Any help would be greatly appreciated.
Thanks, Gordan
Ok,
Turns out that I was using the incorrect property type. Changing RCTDirectEventBlock to RCTBubblingEventBlock did the trick.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With