一:iOS傳遞數(shù)據到RN
1:iOS可以在初始化RCTRootView的時候傳遞props值;
NSURL *jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"RNInteractive" fallbackResource:nil];
NSArray *imageList = @[@{@"name" : @"jj"},
@{@"name" : @"dd"}];
NSDictionary *props = @{@"soure" : imageList};
_rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
moduleName:@"Rninteractive"
initialProperties:props
launchOptions:nil];
2:可以通過appProperties的屬性重新設置props值桐腌;
NSArray *imageList = @[@{@"name" : @"dsssss"},
@{@"name" : @"dfffff"}];
NSDictionary *props = @{@"soure" : imageList};
_rootView.appProperties = props;
3:使用通知方式傳遞數(shù)據到RN
iOS代碼發(fā)送通知:
//需要包含的頭文件
#import <React/RCTEventDispatcher.h>
#import <React/RCTBridge.h>
[self.bridge.eventDispatcher sendAppEventWithName:@"EventNotification"
body:@{@"name": @"nnnnnnn"}];
RN代碼接收通知:
//創(chuàng)建一個監(jiān)聽收到的通知减俏,需要組件NativeAppEventEmitter
var listener = NativeAppEventEmitter.addListener(
'EventNotification', //監(jiān)聽的通知名稱
(reminder) => console.log(reminder.name, '收到的通知')
);
二:RN傳遞數(shù)據到iOS
iOS提供外調的接口崔挖,需要實現(xiàn)RCTBridgeModule協(xié)議
// 必須實現(xiàn)
RCT_EXPORT_MODULE();
//對外提供方法,傳遞字符串
RCT_EXPORT_METHOD(testNormalEvent:(NSString *)name forSomething:(NSString *)thing) {
NSString *info = [NSString stringWithFormat:@"%s: %@\nFor: %@",__FUNCTION__, name, thing];
NSLog(@"%@", info);
}
//對外提供方法舰讹,傳遞字典
RCT_EXPORT_METHOD(testDictEvent:(NSString *)name details:(NSDictionary *) dictionary) {
NSString *info = [NSString stringWithFormat:@"%s: %@\nFor: %@",__FUNCTION__, name, dictionary];
NSLog(@"%@", info);
}
//對外提供方法茅姜,傳遞回調
RCT_EXPORT_METHOD(testCallbackEvent:(NSString *)name cb:(RCTResponseSenderBlock)callback) {
NSLog(@"--%s,----%@",__FUNCTION__, name);
NSArray *events=@[@"你打我看看啊 ", @"test ", @" array"];
callback(@[[NSNull null], events]);
}
//設置常量給RN進行調用
- (NSDictionary *)constantsToExport {
//此處定義的常量為RN通知的通知名
return @{@"receiveNotificationName": @"receive_notification_test"};
}
//對外提供通知方法,接收js的通知
RCT_EXPORT_METHOD(startReceiveNotification:(NSString *)name) {
NSLog(@"--%s--, ----%@", __FUNCTION__, name);
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(calendarEventReminderReceived:)
name:name
object:nil];
}
RN調用iOS提供的方法傳遞數(shù)據
//普通傳遞數(shù)據
touchtestNormalEvent = () => {
console.log('touchtestNormalEvent');
caManager.testNormalEvent('超級無敵帥', '老子是逗比');
};
//字典傳遞
touchtestDictEvent = () => {
console.log('touchtestDictEvent');
caManager.testDictEvent('超級無敵帥2號', {'name': 'wwww', 'age': 18, 'date': date})
};
//閉包回調
touchtestCallbackEvent = () => {
console.log('touchtestCallbackEvent');
caManager.testCallbackEvent('超級無敵帥3號', (error, events) => {
if (error) {
console.log('error =', error)
}else {
console.log('events =', events)
}
})
};
//通知傳遞
touchreceiveNotification = () => {
//receiveNotificationName通知名由iOS原生提供
caManager.startReceiveNotification(caManager.receiveNotificationName);
}
iOS完整代碼:
#import "Test1ViewController.h"
#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>
#import <React/RCTBridgeModule.h>
//#import <React/RCTConvert.h>
#import <React/RCTEventDispatcher.h>
#import <React/RCTBridge.h>
@interface Test1ViewController ()<RCTBridgeModule>
@property (nonatomic, strong) RCTRootView *rootView;
@end
@implementation Test1ViewController
@synthesize bridge = _bridge;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.view.backgroundColor = [UIColor whiteColor];
NSURL *jsCodeLocation;
jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"RNInteractive" fallbackResource:nil];
NSArray *imageList = @[@{@"name" : @"jj"},
@{@"name" : @"dd"}];
NSDictionary *props = @{@"soure" : imageList};
_rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
moduleName:@"Rninteractive"
initialProperties:props
launchOptions:nil];
self.view = _rootView;
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(100, 100, 100, 100);
button.backgroundColor = [UIColor redColor];
[button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
}
- (void)buttonAction:(id)sender {
NSArray *imageList = @[@{@"name" : @"dsssss"},
@{@"name" : @"dfffff"}];
NSDictionary *props = @{@"soure" : imageList};
_rootView.appProperties = props;
}
// 必須實現(xiàn)
RCT_EXPORT_MODULE();
//對外提供方法月匣,傳遞字符串
RCT_EXPORT_METHOD(testNormalEvent:(NSString *)name forSomething:(NSString *)thing) {
NSString *info = [NSString stringWithFormat:@"%s: %@\nFor: %@",__FUNCTION__, name, thing];
NSLog(@"%@", info);
}
//對外提供方法钻洒,傳遞字典
RCT_EXPORT_METHOD(testDictEvent:(NSString *)name details:(NSDictionary *) dictionary) {
NSString *info = [NSString stringWithFormat:@"%s: %@\nFor: %@",__FUNCTION__, name, dictionary];
NSLog(@"%@", info);
}
//對外提供方法,傳遞回調
RCT_EXPORT_METHOD(testCallbackEvent:(NSString *)name cb:(RCTResponseSenderBlock)callback) {
NSLog(@"--%s,----%@",__FUNCTION__, name);
NSArray *events=@[@"你打我看看啊 ", @"test ", @" array"];
callback(@[[NSNull null], events]);
}
//設置常量給JavaScript進行調用
- (NSDictionary *)constantsToExport {
//此處定義的常量為js通知的通知名
return @{@"receiveNotificationName": @"receive_notification_test"};
}
//對外提供通知方法锄开,接收js的通知
RCT_EXPORT_METHOD(startReceiveNotification:(NSString *)name) {
NSLog(@"--%s--, ----%@", __FUNCTION__, name);
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(calendarEventReminderReceived:)
name:name
object:nil];
[[NSNotificationCenter defaultCenter] postNotificationName:name object:@"nnnnnnnn"];
}
//進行設置發(fā)送事件通知給js端
- (void)calendarEventReminderReceived:(NSNotification *)notification {
NSString *name = notification.object;
[self.bridge.eventDispatcher sendAppEventWithName:@"EventNotification"
body:@{@"name": name}];
}
RN完整代碼:
//與原生數(shù)據交互
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
View,
TouchableOpacity,
NativeModules,
Text,
NativeAppEventEmitter
} from 'react-native';
//用來調用Test1ViewController中的方法
var caManager = require('NativeModules').Test1ViewController;
var date = new Date();
var count = 0;
//創(chuàng)建一個監(jiān)聽收到的通知
var listener = NativeAppEventEmitter.addListener(
'EventNotification', //監(jiān)聽的通知名稱
(reminder) => console.log(reminder.name, '收到的通知')
);
export default class Rninteractive extends Component {
constructor(props) {
super(props);
this.state = {
text:'Welcome to React Native!',
name: '快來看看哦',
};
}
//將要開始布局素标,只執(zhí)行一次
componentWillMount() {
console.log('componentWillMount111');
}
//是否需要更新
shouldComponentUpdate() {
console.log('shouldComponentUpdate222')
return true;
}
//布局完成,只執(zhí)行一次
componentDidMount() {
console.log('componentDidMount333');
}
//將要更新布局
componentWillUpdate() {
console.log('componentWillUpdate444');
}
//更新完成
componentDidUpdate() {
console.log('componentDidUpdate555');
}
//接收屬性
componentWillReceiveProps() {
console.log('componentWillReceiveProps666');
}
//卸載
componentWillUnmount() {
//卸載的時候要取消監(jiān)聽
listener.remove();
}
render(){
var welcomeText = this.state.text;
var wename = this.state.name;
var valued = this.props.soure.map(
soure => soure,
);
console.log('render', valued);
return(
<View style={styles.contentView}>
<TouchableOpacity onPress={this.touchtestNormalEvent}>
<Text>
{welcomeText}
</Text>
</TouchableOpacity>
<TouchableOpacity onPress={this.touchtestDictEvent}>
<Text>
{wename}
</Text>
</TouchableOpacity>
<TouchableOpacity onPress={this.touchtestCallbackEvent}>
<Text>
與原生ios傳遞回調函數(shù)
</Text>
</TouchableOpacity>
<TouchableOpacity onPress={this.touchreceiveNotification}>
<Text>
與原生ios通知方式傳遞
</Text>
</TouchableOpacity>
</View>
)
}
//普通傳遞數(shù)據
touchtestNormalEvent = () => {
console.log('touchtestNormalEvent');
caManager.testNormalEvent('超級無敵帥', '老子是逗比');
};
//字典傳遞
touchtestDictEvent = () => {
console.log('touchtestDictEvent');
caManager.testDictEvent('超級無敵帥2號', {'name': 'wwww', 'age': 18, 'date': date})
};
//閉包回調
touchtestCallbackEvent = () => {
console.log('touchtestCallbackEvent');
caManager.testCallbackEvent('超級無敵帥3號', (error, events) => {
if (error) {
console.log('error =', error)
}else {
console.log('events =', events)
}
})
};
//通知傳遞
touchreceiveNotification = () => {
//receiveNotificationName通知名由iOS原生提供
caManager.startReceiveNotification(caManager.receiveNotificationName);
}
}
const styles = StyleSheet.create({
contentView: {
flex: 1,
backgroundColor: '#aff1af',
alignItems: 'center',
justifyContent: 'center',
}
});
AppRegistry.registerComponent('Rninteractive', ()=>Rninteractive);