標籤:
1、直接使用NativeModules組件,“MyCustomModule”其實就是我們的對應的OC工程中的類,“processString“就是類中的方法
/** * 調用iOS模組1 * http://www.cnblogs.com/daomul/ */‘use strict‘;var React = require(‘react-native‘);var { NativeModules,View, Text,ScrollView,StyleSheet,TouchableOpacity } = React;var Message = React.createClass({ getInitialState() { return { text: ‘Goodbye World.‘ }; }, componentDidMount() { NativeModules.MyCustomModule.processString(this.state.text, (text) => { this.setState({text}); }); }, render: function() { return ( <ScrollView style={styles.view}> <Text>{this.state.text}</Text> </ScrollView> ); },});var styles = StyleSheet.create({ view:{margin:20,},});React.AppRegistry.registerComponent(‘HellWorld‘, () => Message);
所以對應OC工程中的實現:通過RCT_EXPORT_MODULE() 似的JS能夠放開OC中的API,與之通訊調用
#import <Foundation/Foundation.h>#import "RCTBridgeModule.h"@interface MyCustomModule : NSObject <RCTBridgeModule>@end#import "MyCustomModule.h"@implementation MyCustomModuleRCT_EXPORT_MODULE();RCT_EXPORT_METHOD(processString:(NSString *)input callback:(RCTResponseSenderBlock)callback){ callback(@[[input stringByReplacingOccurrencesOfString:@"Goodbye" withString:@"Hello"]]);}@end
2、我們還可以通過引入NativeModules的方式,“CalendarVIew”對應的也是OC類名,addEventWithName是方法名,
var CalendarManager = require(‘NativeModules‘).CalendarVIew;CalendarManager.addEventWithName(‘something need to remmber‘,‘ShenZheng NanShan‘);
如果參數很多我們希望通過NSDictionary來傳遞資料,也是可以的,OC端可以做一下Convert的處理:
CalendarManager.addEventWithName(‘something need to remmber‘,{ location: ‘ShenZhen NanShan‘, description: ‘other thingslo‘});
CO端代碼:
#import "CalendarVIew.h"#import "RCTConvert.h"#import "RCTLog.h"@implementation CalendarVIewRCT_EXPORT_MODULE();RCT_EXPORT_METHOD(addEventWithName:(NSString *)name dic:(NSDictionary *)dic){ NSString *localStr = [RCTConvert NSString:dic[@"location"]]; NSString *descStr = [RCTConvert NSString:dic[@"description"]]; RCTLogInfo(@"the name is %@,and the location is %@,%@",name,localStr,descStr);}
React Native ——調用Native Modules的方式