React Native ——調用Native Modules的方式

來源:互聯網
上載者:User

標籤:

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的方式

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.