标签:
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 MyCustomModule RCT_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 CalendarVIew RCT_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的方式
标签:
原文地址:http://www.cnblogs.com/daomul/p/4900739.html