react-native调用ios native方法
|
React Native在设计之初,就考虑到了React Native提供的API,不能够完全的覆盖平台对应的所有API.因此在React Native中可以方便的调用Native的方法,Android上面对应Java方法,IOS上对应Object-C方法。 RCTBridgeModule
#import <Foundation/Foundation.h> #import <UIKit/UIKit.h> #import "RCTBridgeModule.h" @interface RNIOSAlert : NSObject<RCTBridgeModule> @end RCT_EXPORT_MODULE所有实现 #define RCT_EXPORT_MODULE(js_name)
RCT_EXTERN void RCTRegisterModule(Class);
+ (NSString *)moduleName { return @#js_name; }
+ (void)load { RCTRegisterModule(self); }
可以看到 #import "RNIOSAlert.h" @implementation RNIOSAlert RCT_EXPORT_MODULE(); @end RCT_EXPORT_METHOD
#define RCT_EXTERN_REMAP_METHOD(js_name,method)
+ (NSArray<NSString *> *)RCT_CONCAT(__rct_export__,
RCT_CONCAT(js_name,RCT_CONCAT(__LINE__,__COUNTER__))) {
return @[@#js_name,@#method];
}
它的作用是在 #import "RNIOSAlert.h"
@implementation RNIOSAlert
RCT_EXPORT_MODULE();
RCT_EXPORT_METHOD(show:(NSString *)msg){
UIAlertView * alertView=[[UIAlertView alloc] initWithTitle:@"react-native" message:msg delegate:nil cancelButtonTitle:@"关闭" otherButtonTitles:nil,nil];
[alertView show];
}
@end
JavaScript调用在JavaScript中调用Object-C定义的方法,需要先导入 import {
StyleSheet,Text,View,NativeModules,TouchableOpacity
} from "react-native";
var RNIOSAlert = NativeModules.RNIOSAlert;
class RNIos extends Component {
render() {
return (
<View style={styles.container}>
<TouchableOpacity onPress={()=>RNIOSAlert.show('from react native ')}>
<Text>Alert</Text>
</TouchableOpacity>
</View>
);
}
}
成功调用
参数
另外React Navite还提供了 RCT_EXPORT_METHOD(showTime:(NSDictionary*)dict){
NSDate * date =[RCTConvert NSDate:dict[@"time"]];
UIAlertView * alertView=[[UIAlertView alloc] initWithTitle:@"react-native" message:[date description] delegate:nil cancelButtonTitle:@"关闭" otherButtonTitles:nil,nil];
[alertView show];
}
这里使用 ......
<TouchableOpacity onPress={()=> {
var date = new Date();
RNIOSAlert.showTime(
{
time: date.getTime()
}
)
}}>
<Text>Time</Text>
</TouchableOpacity>
......
源代码地址:https://github.com/jjz/react-... (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
