一、RN调用OC
- OC部分:新建一个继承NSObject的类RNHelper,导入React/RCTBridgeModule.h头文件,并遵循RCTBridgeModule协议。
RNHelper.h
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface RNHelper : NSObject
@end
NS_ASSUME_NONNULL_END
RNHelper.m
#import "RNHelper.h"
#import <React/RCTBridgeModule.h>
@interface RNHelper () <RCTBridgeModule>
@end
@implementation RNHelper
RCT_EXPORT_MODULE();
RCT_EXPORT_METHOD(getVersion:(RCTResponseSenderBlock)callback) {
NSDictionary * infoDict = [[NSBundle mainBundle] infoDictionary];
NSString * appCurVersion = [infoDict objectForKey:@"CFBundleShortVersionString"];
callback(@[[NSNull null], appCurVersion]);
}
- JS部分:导入头文件,生命一个全局变量
import { NativeModules } from 'react-native';
var helper = NativeModules.RNHelper;
在来一个按钮
<TouchableOpacity onPress={this.onPage.bind(this)}>
<Button
style={{fontSize: 20, color: 'green'}}
styleDisabled={{color: 'red'}}
onPress={() => this.onPage()}
title="RN调用OC"
>
Press Me
</Button>
</TouchableOpacity>
点击事件
onPage(){
helper.getVersion((error, callback) => {
if (callback) {
alert(callback);
}
});
}