React Native原生与JS层交互

最近在对《React Native移动开发实战》一书进行部分修订和升级。在React Native开发中,免不了会涉及到原生代码与JS层的消息传递等问题,那么React Native究竟是如何实现与原生的互相操作的呢?

原生给React Native传参

原生给React Native传值

原生给JS传值,主要依靠属性,也就是通过initialProperties,这个RCTRootView的初始化函数的参数来完成。通过RCTRootView的初始化函数你可以将任意属性传递给React Native应用,参数initialProperties必须是NSDictionary的一个实例。RCTRootView有一个appProperties属性,修改这个属性,JS端会调用相应的渲染方法。

使用RCTRootView将React Natvie视图封装到原生组件中。RCTRootView是一个UIView容器,承载着React Native应用。同时它也提供了一个联通原生端和被托管端的接口。

例如有下面一段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层的处理:

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"]}}. 

使用appProperties进行参数传递

RCTRootView同样提供了一个可读写的属性appProperties。在appProperties设置之后,React Native应用将会根据新的属性重新渲染。当然,只有在新属性和旧的属性有更改时更新才会被触发。

NSArray *imageList = @[@"http://foo.com/bar3.png",
                   @"http://foo.com/bar4.png"];
rootView.appProperties = @{@"images" : imageList};

可以随时更新属性,但是更新必须在主线程中进行,读取则可以在任何线程中进行。

React Native执行原生方法及回调

React Native执行原生方法

.h的文件代码:

#import <Foundation/Foundation.h>
#import <RCTBridgeModule.h>

@interface wjyTestManager : NSObject<RCTBridgeModule>


@end

.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类的名字。

扫描二维码关注公众号,回复: 1939581 查看本文章

并且必须明确的声明要给Javascript导出的方法,否则React Native不会导出任何方法。OC中声明要给Javascript导出的方法,通过RCT_EXPORT_METHOD()宏来实现。

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,你必须通过回调或者触发事件来进行。

传参并回调

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>

        );
      }
}

参数类型说明

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中可以这样订阅事件,通常需要在componentWillUnmount函数中取消事件的订阅。

import { NativeAppEventEmitter } from 'react-native';

var subscription = NativeAppEventEmitter.addListener(
  'EventReminder',
  (reminder) => console.log(reminder.name)
);
...
// 千万不要忘记忘记取消订阅, 通常在componentWillUnmount函数中实现。
subscription.remove();

用NativeAppEventEmitter.addListener中注册一个通知,之后再OC中通过bridge.eventDispatcher sendAppEventWithName发送一个通知,这样就形成了调用关系。

猜你喜欢

转载自blog.csdn.net/xiangzhihong8/article/details/80952666