How to access native UI components' instance methods in React Native

前端 未结 2 847
孤城傲影
孤城傲影 2020-12-24 14:44

We can control custom native UI components\' properties by exporting native properties using RCT_EXPORT_VIEW_PROPERTY.

But how to export instance method

2条回答
  •  暖寄归人
    2020-12-24 15:24

    I'm not an Objective C expert but a Swift developer.

    I better use this way just for readability (maybe there are drawbacks in Obj-C?):

    • In Manager: store a reference to your view in an instance private property
    • it will then help to call your view's method

    Obj-C side - component manager:

    @implementation RNAnalogClockManager {
      RNAnalogClock* _AnalogClock;
    }
    
    RCT_EXPORT_MODULE()
    
    - (UIView *)view
    {
      // keep a reference to the view before returning it
      _AnalogClock = [[RNAnalogClock alloc] init];
      return _AnalogClock;
    }
    
    // export method and easily call view method 
    RCT_EXPORT_METHOD(startRealTime) {
      [_AnalogClock startRealTime];
    };
    

    JS side remains the same

    NOTE: I don't need callback in my example but it does not change the principle it is just another parameter.

提交回复
热议问题