你的位置:首页 > 操作系统

[操作系统]React Native知识12


一:原生传递参数给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 wjyTestManagerRCT_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:传参并带有回调

// 对外提供调用方法,演示CallbackRCT_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);}// 对外提供调用方法,为了演示事件时间格式化 secondsSinceUnixEpochRCT_EXPORT_METHOD(testDateEventOne:(NSString *)name forSomething:(NSString *)thing data:(NSNumber*)secondsSinceUnixEpoch){  NSDate *date = [RCTConvert NSDate:secondsSinceUnixEpoch];  [self showDate:date withName:name forSomething:thing];}// 对外提供调用方法,为了演示事件时间格式化 ISO8601DateStringRCT_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);}// 对外提供调用方法,演示CallbackRCT_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);