React Native知識12-與原生交互

来源:http://www.cnblogs.com/wujy/archive/2016/09/12/5864591.html
-Advertisement-
Play Games

一:原生傳遞參數給React Native 1:原生給React Native傳參 原生給JS傳數據,主要依靠屬性。 通過initialProperties,這個RCTRootView的初始化函數的參數來完成。 RCTRootView還有一個appProperties屬性,修改這個屬性,JS端會調用 ...


一:原生傳遞參數給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);

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • API-https://developer.apple.com/library/ios/documentation/Performance/Reference/GCD_libdispatch_Ref/index.html#//apple_ref/doc/uid/TP40008079 一、同步、非同步和 ...
  • 有時應用程式需要能夠進行自定義繪圖。我們可以依靠兩個不同的庫來滿足我們的繪圖需要。一個庫是Quartz 2D,它是Core Graphics框架的一部分;另一個庫是OpenGL ES,它是跨平臺的圖形庫。OpenGL ES是跨平臺圖形庫OpenGL的簡化版。OpenGL ES是OpenGL的一個子集 ...
  • Android 樣式 android中的樣式和CSS樣式作用相似,都是用於為界面元素定義顯示風格,它是一個包含一個或者多個view控制項屬性的集合。如:需要定義字體的顏色和大小。 在CSS中是這樣定義的: 可以像這樣使用上面的css樣式:<div class="wu">wuyudong‘blog</d ...
  • http://blog.sina.com.cn/s/blog_45e2b66c01019wfg.html UIScrollView 快速滑動過程中,滾動速度過快,可以通過屬性decelerationRate控制。 decelerationRate範圍為0 1,一般0 0.5沒有多少區別。0也沒有問題 ...
  • 中文 iOS/Mac 開發博客列表 ...
  • 前言: 項目是基於平板開發的,設計的界面是要求橫屏展示界面。所以我將所有的Activity都強制設置為橫屏 問題: 主界面,最常見的Activity+n個Fragment 我這裡使用的hide、show Fragment的方式來切換Fragment,當關閉手機、平板屏幕再打開,會發現Fragment ...
  • 1 #import "Cat.h" 2 3 @interface Cat () 4 5 @property (nonatomic, copy) NSString *name; 6 7 @end 8 9 @implementation Cat{ 10 int age; 11 } 12 13 -(ins ...
  • 記錄字元串的處理,不是一個簡單的工作。 NSString是代碼中隨處可見的類型,也是應用和處理繁多的對象,在此只記錄需要常備的方法,並且加以說明。 說明: 1.計算字元串尺寸的方法,sizeWithFont系列方法已經被廢物,建議改為boundingRectWithSize方法;NSAttribut ...
一周排行
    -Advertisement-
    Play Games
  • 前言 本文介紹一款使用 C# 與 WPF 開發的音頻播放器,其界面簡潔大方,操作體驗流暢。該播放器支持多種音頻格式(如 MP4、WMA、OGG、FLAC 等),並具備標記、實時歌詞顯示等功能。 另外,還支持換膚及多語言(中英文)切換。核心音頻處理採用 FFmpeg 組件,獲得了廣泛認可,目前 Git ...
  • OAuth2.0授權驗證-gitee授權碼模式 本文主要介紹如何筆者自己是如何使用gitee提供的OAuth2.0協議完成授權驗證並登錄到自己的系統,完整模式如圖 1、創建應用 打開gitee個人中心->第三方應用->創建應用 創建應用後在我的應用界面,查看已創建應用的Client ID和Clien ...
  • 解決了這個問題:《winForm下,fastReport.net 從.net framework 升級到.net5遇到的錯誤“Operation is not supported on this platform.”》 本文內容轉載自:https://www.fcnsoft.com/Home/Sho ...
  • 國內文章 WPF 從裸 Win 32 的 WM_Pointer 消息獲取觸摸點繪製筆跡 https://www.cnblogs.com/lindexi/p/18390983 本文將告訴大家如何在 WPF 裡面,接收裸 Win 32 的 WM_Pointer 消息,從消息裡面獲取觸摸點信息,使用觸摸點 ...
  • 前言 給大家推薦一個專為新零售快消行業打造了一套高效的進銷存管理系統。 系統不僅具備強大的庫存管理功能,還集成了高性能的輕量級 POS 解決方案,確保頁面載入速度極快,提供良好的用戶體驗。 項目介紹 Dorisoy.POS 是一款基於 .NET 7 和 Angular 4 開發的新零售快消進銷存管理 ...
  • ABP CLI常用的代碼分享 一、確保環境配置正確 安裝.NET CLI: ABP CLI是基於.NET Core或.NET 5/6/7等更高版本構建的,因此首先需要在你的開發環境中安裝.NET CLI。這可以通過訪問Microsoft官網下載並安裝相應版本的.NET SDK來實現。 安裝ABP ...
  • 問題 問題是這樣的:第三方的webapi,需要先調用登陸介面獲取Cookie,訪問其它介面時攜帶Cookie信息。 但使用HttpClient類調用登陸介面,返回的Headers中沒有找到Cookie信息。 分析 首先,使用Postman測試該登陸介面,正常返回Cookie信息,說明是HttpCli ...
  • 國內文章 關於.NET在中國為什麼工資低的分析 https://www.cnblogs.com/thinkingmore/p/18406244 .NET在中國開發者的薪資偏低,主要因市場需求、技術棧選擇和企業文化等因素所致。歷史上,.NET曾因微軟的閉源策略發展受限,儘管後來推出了跨平臺的.NET ...
  • 在WPF開發應用中,動畫不僅可以引起用戶的註意與興趣,而且還使軟體更加便於使用。前面幾篇文章講解了畫筆(Brush),形狀(Shape),幾何圖形(Geometry),變換(Transform)等相關內容,今天繼續講解動畫相關內容和知識點,僅供學習分享使用,如有不足之處,還請指正。 ...
  • 什麼是委托? 委托可以說是把一個方法代入另一個方法執行,相當於指向函數的指針;事件就相當於保存委托的數組; 1.實例化委托的方式: 方式1:通過new創建實例: public delegate void ShowDelegate(); 或者 public delegate string ShowDe ...