一:原生傳遞參數給React Native
1:原生給React Native傳參
原生給JS傳數據,主要依靠屬性。
通過initialProperties,這個RCTRootView的初始化函數的參數來完成。
RCTRootView還有一個appProperties屬性,修改這個屬性,JS端會調用相應的渲染方法。
我們使用RCTRootView將React Natvie視圖封裝到原生組件中。RCTRootView是一個UIView容器,承載着React Native應用。同時它也提供了一個聯通原生端和被托管端的接口。
通過RCTRootView的初始化函數你可以將任意屬性傳遞給React Native應用。參數initialProperties必須是NSDictionary的一個實例。這一字典參數會在內部被轉化為一個可供JS組件調用的JSON對象。
原生oc代碼:
NSURL *jsCodeLocation; jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index.ios" fallbackResource:nil]; NSArray *imageList = @[@"http://foo.com/bar1.png", @"http://foo.com/bar2.png"]; NSDictionary *wjyprops = @{@"images" : imageList}; RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation moduleName:@"ReactNativeProject" initialProperties:wjyprops launchOptions:launchOptions];
js處理代碼:
'use strict'; import React, { Component } from 'react'; import { AppRegistry, View, Image, } from 'react-native'; class ImageBrowserApp extends Component { renderImage(imgURI) { return ( <Image source={{uri: imgURI}} /> ); } render() { return ( <View> {this.props.images.map(this.renderImage)} </View> ); } } AppRegistry.registerComponent('ImageBrowserApp', () => ImageBrowserApp);
注意:不管OC中關於initialProperties的字典名字叫什么,在JS中都是this.props開頭,然后接下來才是字典里面的key名字;下面是打印出來的值;
{"rootTag":1,"initialProps":{"images":["http://foo.com/bar1.png","http://foo.com/bar2.png"]}}.
2:使用appProperties進行傳遞,原生給React Native傳參
RCTRootView同樣提供了一個可讀寫的屬性appProperties。在appProperties設置之后,React Native應用將會根據新的屬性重新渲染。當然,只有在新屬性和之前的屬性有區別時更新才會被觸發。
NSArray *imageList = @[@"http://foo.com/bar3.png", @"http://foo.com/bar4.png"]; rootView.appProperties = @{@"images" : imageList};
你可以隨時更新屬性,但是更新必須在主線程中進行,讀取則可以在任何線程中進行。
更新屬性時並不能做到只更新一部分屬性。我們建議你自己封裝一個函數來構造屬性。
注意:目前,最頂層的RN組件(即registerComponent方法中調用的那個)的componentWillReceiveProps和componentWillUpdateProps方法在屬性更新后不會觸發。但是,你可以通過componentWillMount訪問新的屬性值。
二:React Native執行原生的方法及回調
1:React Native執行原生的方法
.h的文件內容:
#import <Foundation/Foundation.h> #import <RCTBridgeModule.h> @interface wjyTestManager : NSObject<RCTBridgeModule> @end
注意:在React Native中,一個“原生模塊”就是一個實現了“RCTBridgeModule”協議的Objective-C類,其中RCT是ReaCT的縮寫。
.m的文件內容:
#import "wjyTestManager.h" @implementation wjyTestManager RCT_EXPORT_MODULE(); RCT_EXPORT_METHOD(doSomething:(NSString *)aString withA:(NSString *)a) { NSLog(@"%@,%@",aString,a); } @end
注意:為了實現RCTBridgeModule協議,你的類需要包含RCT_EXPORT_MODULE()宏。這個宏也可以添加一個參數用來指定在Javascript中訪問這個模塊的名字。如果你不指定,默認就會使用這個Objective-C類的名字。你必須明確的聲明要給Javascript導出的方法,否則React Native不會導出任何方法。OC中聲明要給Javascript導出的方法,通過RCT_EXPORT_METHOD()宏來實現:
js相關代碼如下:
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Alert,
TouchableHighlight,
} from 'react-native';
import {
NativeModules,
NativeAppEventEmitter
} from 'react-native';
var CalendarManager = NativeModules.wjyTestManager;
class ReactNativeProject extends Component {
render() {
return (
<TouchableHighlight onPress={()=>CalendarManager.doSomething('sdfsdf','sdfsdfs')}>
<Text style={styles.text}
>點擊 </Text>
</TouchableHighlight>
);
}
}
const styles = StyleSheet.create({
text: {
flex: 1,
marginTop: 55,
fontWeight: 'bold'
},
});
AppRegistry.registerComponent('ReactNativeProject', () => ReactNativeProject);
注意:要用到NativeModules則要引入相應的命名空間import { NativeModules } from 'react-native’;然后再進行調用CalendarManager.doSomething('sdfsdf','sdfsdfs’);橋接到Javascript的方法返回值類型必須是void。React Native的橋接操作是異步的,所以要返回結果給Javascript,你必須通過回調或者觸發事件來進行。
2:傳參並帶有回調
// 對外提供調用方法,演示Callback RCT_EXPORT_METHOD(testCallbackEvent:(NSDictionary *)dictionary callback:(RCTResponseSenderBlock)callback) { NSLog(@"當前名字為:%@",dictionary); NSArray *events=@[@"callback ", @"test ", @" array"]; callback(@[[NSNull null],events]); }
注意:第一個參數代表從JavaScript傳過來的數據,第二個參數是回調方法;
JS代碼如下:
import { NativeModules, NativeAppEventEmitter } from 'react-native'; var CalendarManager = NativeModules.wjyTestManager; class ReactNativeProject extends Component { render() { return ( <TouchableHighlight onPress={()=>{CalendarManager.testCallbackEvent( {'name':'good','description':'http://www.lcode.org'}, (error,events)=>{ if(error){ console.error(error); }else{ this.setState({events:events}); } })}} > <Text style={styles.text} >點擊 </Text> </TouchableHighlight> ); } }
3:參數類型
RCT_EXPORT_METHOD 支持所有標准JSON類型,包括:
string (NSString)
number (NSInteger, float, double, CGFloat, NSNumber)
boolean (BOOL, NSNumber)
array (NSArray) 包含本列表中任意類型
object (NSDictionary) 包含string類型的鍵和本列表中任意類型的值
function (RCTResponseSenderBlock)
除此以外,任何RCTConvert類支持的的類型也都可以使用(參見RCTConvert了解更多信息)。RCTConvert還提供了一系列輔助函數,用來接收一個JSON值並轉換到原生Objective-C類型或類。例如
#import "RCTConvert.h" #import "RCTBridge.h" #import "RCTEventDispatcher.h" // 對外提供調用方法,為了演示事件傳入屬性字段 RCT_EXPORT_METHOD(testDictionaryEvent:(NSString *)name details:(NSDictionary *) dictionary) { NSString *location = [RCTConvert NSString:dictionary[@"thing"]]; NSDate *time = [RCTConvert NSDate:dictionary[@"time"]]; NSString *description=[RCTConvert NSString:dictionary[@"description"]]; NSString *info = [NSString stringWithFormat:@"Test: %@\nFor: %@\nTestTime: %@\nDescription: %@",name,location,time,description]; NSLog(@"%@", info); }
三: iOS原生訪問調用React Native
如果我們需要從iOS原生方法發送數據到JavaScript中,那么使用eventDispatcher。
#import "RCTBridge.h" #import "RCTEventDispatcher.h" @implementation CalendarManager @synthesize bridge = _bridge; // 進行設置發送事件通知給JavaScript端 - (void)calendarEventReminderReceived:(NSNotification *)notification { NSString *name = [notification userInfo][@"name"]; [self.bridge.eventDispatcher sendAppEventWithName:@"EventReminder" body:@{@"name": name}]; } @end
在JavaScript中可以這樣訂閱事件:
import { NativeAppEventEmitter } from 'react-native';
var subscription = NativeAppEventEmitter.addListener(
'EventReminder',
(reminder) => console.log(reminder.name)
);
...
// 千萬不要忘記忘記取消訂閱, 通常在componentWillUnmount函數中實現。
subscription.remove();
注意:用NativeAppEventEmitter.addListener中注冊一個通知,之后再OC中通過bridge.eventDispatcher sendAppEventWithName發送一個通知,這樣就形成了調用關系。
四:代碼段內容:
#import "CalendarManager.h" #import "RCTConvert.h" #import "RCTBridge.h" #import "RCTEventDispatcher.h" @implementation CalendarManager @synthesize bridge=_bridge; // 默認名稱 RCT_EXPORT_MODULE() /** // 指定執行模塊里的方法所在的隊列 - (dispatch_queue_t)methodQueue { return dispatch_get_main_queue(); } */ // 在完整demo中才有用到,用於更新原生UI - (void)showInfo:(NSString *)info { // 更新UI操作在主線程中執行 dispatch_async(dispatch_get_main_queue(), ^{ //Update UI in UI thread here [[NSNotificationCenter defaultCenter] postNotificationName:@"react_native_test" object:nil userInfo:@{@"info": info}]; }); } - (void)showDate:(NSDate *)date withName:(NSString *)name forSomething:(NSString *)thing { NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ; [formatter setDateFormat:@"yyyy-MM-dd"]; NSString *info = [NSString stringWithFormat:@"Test: %@\nFor: %@\nTestTime: %@", name, thing,[formatter stringFromDate:date]]; NSLog(@"%@", info); } // 對外提供調用方法 RCT_EXPORT_METHOD(testNormalEvent:(NSString *)name forSomething:(NSString *)thing) { NSString *info = [NSString stringWithFormat:@"Test: %@\nFor: %@", name, thing]; NSLog(@"%@", info); } // 對外提供調用方法,為了演示事件時間格式化 secondsSinceUnixEpoch RCT_EXPORT_METHOD(testDateEventOne:(NSString *)name forSomething:(NSString *)thing data:(NSNumber*)secondsSinceUnixEpoch) { NSDate *date = [RCTConvert NSDate:secondsSinceUnixEpoch]; [self showDate:date withName:name forSomething:thing]; } // 對外提供調用方法,為了演示事件時間格式化 ISO8601DateString RCT_EXPORT_METHOD(testDateEventTwo:(NSString *)name forSomething:(NSString *)thing date:(NSString *)ISO8601DateString) { NSDate *date = [RCTConvert NSDate:ISO8601DateString]; [self showDate:date withName:name forSomething:thing]; } // 對外提供調用方法,為了演示事件時間格式化 自動類型轉換 RCT_EXPORT_METHOD(testDateEvent:(NSString *)name forSomething:(NSString *)thing date:(NSDate *)date) { [self showDate:date withName:name forSomething:thing]; } // 對外提供調用方法,為了演示事件傳入屬性字段 RCT_EXPORT_METHOD(testDictionaryEvent:(NSString *)name details:(NSDictionary *) dictionary) { NSString *location = [RCTConvert NSString:dictionary[@"thing"]]; NSDate *time = [RCTConvert NSDate:dictionary[@"time"]]; NSString *description=[RCTConvert NSString:dictionary[@"description"]]; NSString *info = [NSString stringWithFormat:@"Test: %@\nFor: %@\nTestTime: %@\nDescription: %@",name,location,time,description]; NSLog(@"%@", info); } // 對外提供調用方法,演示Callback RCT_EXPORT_METHOD(testCallbackEvent:(RCTResponseSenderBlock)callback) { NSArray *events=@[@"callback ", @"test ", @" array"]; callback(@[[NSNull null],events]); } // 對外提供調用方法,演示Promise使用 RCT_REMAP_METHOD(testPromiseEvent, resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject) { NSArray *events =@[@"Promise ",@"test ",@" array"]; if (events) { resolve(events); } else { NSError *error=[NSError errorWithDomain:@"我是Promise回調錯誤信息..." code:101 userInfo:nil]; reject(@"no_events", @"There were no events", error); } } // 對外提供調用方法,演示Thread使用 RCT_EXPORT_METHOD(doSomethingExpensive:(NSString *)param callback:(RCTResponseSenderBlock)callback) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ // 在后台執行耗時操作 // You can invoke callback from any thread/queue callback(@[[NSNull null],@"耗時操作執行完成..."]); }); } // 進行設置封裝常量給JavaScript進行調用 -(NSDictionary *)constantsToExport { // 此處定義的常量為js訂閱原生通知的通知名 return @{@"receiveNotificationName":@"receive_notification_test"}; } // 開始訂閱通知事件 RCT_EXPORT_METHOD(startReceiveNotification:(NSString *)name) { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(calendarEventReminderReceived:) name:name object:nil]; } // 進行設置發送事件通知給JavaScript端(這里需要注意,差一個觸發通知點,需自己想辦法加上,或者看完整demo) - (void)calendarEventReminderReceived:(NSNotification *)notification { NSString *name = [notification userInfo][@"name"]; [self.bridge.eventDispatcher sendAppEventWithName:@"EventReminder" body:@{@"name": name}]; } @end
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
ScrollView,
TouchableHighlight
} from 'react-native';
import {
NativeModules,
NativeAppEventEmitter
} from 'react-native';
var subscription;
var CalendarManager = NativeModules.CalendarManager;
class CustomButton extends React.Component {
render() {
return (
<TouchableHighlight
style={{padding: 8, backgroundColor:this.props.backgroundColor}}
underlayColor="#a5a5a5"
onPress={this.props.onPress}>
<Text>{this.props.text}</Text>
</TouchableHighlight>
);
}
}
class ModulesDemo extends Component {
constructor(props){
super(props);
this.state={
events:'',
notice:'',
}
}
componentDidMount(){
console.log('開始訂閱通知...');
this.receiveNotification();
subscription = NativeAppEventEmitter.addListener(
'EventReminder',
(reminder) => {
console.log('通知信息:'+reminder.name)
this.setState({notice:reminder.name});
}
);
}
receiveNotification(){
// CalendarManager.receiveNotificationName 為原生定義常量
CalendarManager.startReceiveNotification(CalendarManager.receiveNotificationName);
}
componentWillUnmount(){
subscription.remove();
}
//獲取Promise對象處理
async updateEvents(){
console.log('updateEvents');
try{
var events=await CalendarManager.testPromiseEvent();
this.setState({events});
}catch(e){
console.error(e);
}
}
render() {
var date = new Date();
return (
<ScrollView>
<View>
<Text style={{fontSize: 16, textAlign: 'center', margin: 10}}>
RN模塊
</Text>
<View style={{borderWidth: 1,borderColor: '#000000'}}>
<Text style={{fontSize: 15, margin: 10}}>
普通調用原生模塊方法
</Text>
<CustomButton text="調用testNormalEvent方法-普通"
backgroundColor= "#FF0000"
onPress={()=>CalendarManager.testNormalEvent('調用testNormalEvent方法', '測試普通調用')}
/>
<CustomButton text="調用testDateEvent方法-日期處理"
backgroundColor= "#FF7F00"
onPress={()=>CalendarManager.testDateEvent('調用testDateEvent方法', '測試date格式',date.getTime())}
/>
<CustomButton text="調用testDictionaryEvent方法-字典"
backgroundColor= "#FFFF00"
onPress={()=>CalendarManager.testDictionaryEvent('調用testDictionaryEvent方法', {
thing:'測試字典(字段)格式',
time:date.getTime(),
description:'就是這么簡單~'
})}
/>
</View>
<View>
<Text style={{fontSize: 15, margin: 10}}>
'Callback返回數據:{this.state.events}
</Text>
<CustomButton text="調用原生模塊testCallbackEvent方法-Callback"
backgroundColor= "#00FF00"
onPress={()=>CalendarManager.testCallbackEvent((error,events)=>{
if(error){
console.error(error);
}else{
this.setState({events:events,});
}
}
)}
/>
<CustomButton text="調用原生模塊testPromiseEvent方法-Promise"
backgroundColor= "#00FFFF"
onPress={()=>this.updateEvents()}
/>
</View>
<View style={{borderWidth: 1,borderColor: '#000000'}}>
<Text style={{fontSize: 15, margin: 10}}>
原生調js,接收信息:{this.state.notice}
</Text>
</View>
</View>
</ScrollView>
);
}
}
AppRegistry.registerComponent('NativeTest', () => ModulesDemo);
最近有個妹子弄的一個關於擴大眼界跟內含的訂閱號,每天都會更新一些深度內容,在這里如果你感興趣也可以關注一下(嘿對美女跟知識感興趣),當然可以關注后輸入:github 會有我的微信號,如果有問題你也可以在那找到我;當然不感興趣無視此信息;

