Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling RCTDirectEventBlock doesn't trigger JS code

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

like image 311
ggordan Avatar asked Apr 14 '26 12:04

ggordan


1 Answers

Ok,

Turns out that I was using the incorrect property type. Changing RCTDirectEventBlock to RCTBubblingEventBlock did the trick.

like image 163
ggordan Avatar answered Apr 16 '26 05:04

ggordan