React-Native 学习RN和iOS交互

一:iOS传递数据到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:使用通知方式传递数据到RN

iOS代码发送通知:
//需要包含的头文件
#import 
#import 
[self.bridge.eventDispatcher sendAppEventWithName:@"EventNotification"
                                               body:@{@"name": @"nnnnnnn"}];
RN代码接收通知:
//创建一个监听收到的通知,需要组件NativeAppEventEmitter
var listener = NativeAppEventEmitter.addListener(
    'EventNotification', //监听的通知名称
    (reminder) => console.log(reminder.name, '收到的通知')
);

二:RN传递数据到iOS
iOS提供外调的接口,需要实现RCTBridgeModule协议

//  必须实现
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提供的方法传递数据

//普通传递数据
    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 
#import 
#import 
//#import 
#import 
#import 


@interface Test1ViewController ()

@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;
}

//  必须实现
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"];
}
//进行设置发送事件通知给js端
- (void)calendarEventReminderReceived:(NSNotification *)notification {
  NSString *name = notification.object;
  [self.bridge.eventDispatcher sendAppEventWithName:@"EventNotification"
                                               body:@{@"name": name}];
}

RN完整代码:

//与原生数据交互
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;
//创建一个监听收到的通知
var listener = NativeAppEventEmitter.addListener(
    'EventNotification', //监听的通知名称
    (reminder) => console.log(reminder.name, '收到的通知')
);

export default class Rninteractive extends Component {
    constructor(props) {
        super(props);
        this.state = {
            text:'Welcome to React Native!',
            name: '快来看看哦',
        };
    }
    //将要开始布局,只执行一次
    componentWillMount() {
        console.log('componentWillMount111');
    }
    //是否需要更新
    shouldComponentUpdate() {
        console.log('shouldComponentUpdate222')
        return true;
    }
    //布局完成,只执行一次
    componentDidMount() {
        console.log('componentDidMount333');
    }
    //将要更新布局
    componentWillUpdate() {
        console.log('componentWillUpdate444');
    }
    //更新完成
    componentDidUpdate() {
        console.log('componentDidUpdate555');
    }
    //接收属性
    componentWillReceiveProps() {
        console.log('componentWillReceiveProps666');
    }
    //卸载
    componentWillUnmount() {
        //卸载的时候要取消监听
        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(
            
                
                    
                        {welcomeText}
                    
                
                
                    
                        {wename}
                    
                
                
                    
                        与原生ios传递回调函数
                    
                
                
                    
                        与原生ios通知方式传递
                    
                
            
        )
    }

    //普通传递数据
    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);

你可能感兴趣的:(React-Native 学习RN和iOS交互)