<address id="ttjl9"></address>

      <noframes id="ttjl9"><address id="ttjl9"><nobr id="ttjl9"></nobr></address>
      <form id="ttjl9"></form>
        <em id="ttjl9"><span id="ttjl9"></span></em>
        <address id="ttjl9"></address>

          <noframes id="ttjl9"><form id="ttjl9"></form>

          React Native原生與JS層交互

          2018-7-2    seo達人

          如果您想訂閱本博客內容,每天自動發到您的郵箱中, 請點這里

          最近在對《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];
              
          • 1
          • 2
          • 3
          • 4
          • 5
          • 6
          • 7
          • 8
          • 9
          • 10
          • 11
          • 12
          • 13
          • 14

          下面是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);
              
          • 1
          • 2
          • 3
          • 4
          • 5
          • 6
          • 7
          • 8
          • 9
          • 10
          • 11
          • 12
          • 13
          • 14
          • 15
          • 16
          • 17
          • 18
          • 19
          • 20
          • 21
          • 22
          • 23

          不管OC中關于initialProperties的名字叫什么,在JS中都是this.props開頭,然后接下來才是key名字。

          {"rootTag":1,"initialProps":{"images":["http://foo.com/bar1.png","http://foo.com/bar2.png"]}}. 
              
          • 1

          使用appProperties進行參數傳遞

          RCTRootView同樣提供了一個可讀寫的屬性appProperties。在appProperties設置之后,React Native應用將會根據新的屬性重新渲染。當然,只有在新屬性和舊的屬性有更改時更新才會被觸發。

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

          可以隨時更新屬性,但是更新必須在主線程中進行,讀取則可以在任何線程中進行。

          React Native執行原生方法及回調

          React Native執行原生方法

          .h的文件代碼:

          #import <Foundation/Foundation.h> #import <RCTBridgeModule.h> @interface wjyTestManager : NSObject<RCTBridgeModule> @end
              
          • 1
          • 2
          • 3
          • 4
          • 5
          • 6
          • 7

          .m的文件代碼:

          #import "wjyTestManager.h" @implementation wjyTestManager RCT_EXPORT_MODULE();
          
          RCT_EXPORT_METHOD(doSomething:(NSString *)aString withA:(NSString *)a)
          { NSLog(@"%@,%@",aString,a);
          } @end
              
          • 1
          • 2
          • 3
          • 4
          • 5
          • 6
          • 7
          • 8
          • 9
          • 10
          • 11
          • 12

          為了實現RCTBridgeModule協議,你的類需要包含RCT_EXPORT_MODULE()宏。這個宏也可以添加一個參數用來指定在Javascript中訪問這個模塊的名字。如果你不指定,默認就會使用這個Objective-C類的名字。

          并且必須明確的聲明要給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);
              
          • 1
          • 2
          • 3
          • 4
          • 5
          • 6
          • 7
          • 8
          • 9
          • 10
          • 11
          • 12
          • 13
          • 14
          • 15
          • 16
          • 17
          • 18
          • 19
          • 20
          • 21
          • 22
          • 23
          • 24
          • 25
          • 26
          • 27
          • 28
          • 29
          • 30
          • 31
          • 32
          • 33
          • 34
          • 35
          • 36
          • 37
          • 38

          要用到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]);
          }
              
          • 1
          • 2
          • 3
          • 4
          • 5
          • 6

          說明:第一個參數代表從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>
          
                  );
                }
          }
              
          • 1
          • 2
          • 3
          • 4
          • 5
          • 6
          • 7
          • 8
          • 9
          • 10
          • 11
          • 12
          • 13
          • 14
          • 15
          • 16
          • 17
          • 18
          • 19
          • 20
          • 21
          • 22
          • 23
          • 24
          • 25
          • 26
          • 27

          參數類型說明

          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);
          }
              
          • 1
          • 2
          • 3
          • 4
          • 5
          • 6
          • 7
          • 8
          • 9
          • 10
          • 11
          • 12
          • 13
          • 14

          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
              
          • 1
          • 2
          • 3
          • 4
          • 5
          • 6
          • 7
          • 8
          • 9
          • 10
          • 11
          • 12
          • 13
          • 14
          • 15
          • 16

          在JavaScript中可以這樣訂閱事件,通常需要在componentWillUnmount函數中取消事件的訂閱。

          import { NativeAppEventEmitter } from 'react-native';
          
          var subscription = NativeAppEventEmitter.addListener( 'EventReminder',
            (reminder) => console.log(reminder.name)
          ); ... // 千萬不要忘記忘記取消訂閱, 通常在componentWillUnmount函數中實現。
          subscription.remove();
              
          • 1
          • 2
          • 3
          • 4
          • 5
          • 6
          • 7
          • 8
          • 9

          用NativeAppEventEmitter.addListener中注冊一個通知,之后再OC中通過bridge.eventDispatcher sendAppEventWithName發送一個通知,這樣就形成了調用關系。

          藍藍設計www.syprn.cn )是一家專注而深入的界面設計公司,為期望卓越的國內外企業提供卓越的UI界面設計、BS界面設計 、 cs界面設計 、 ipad界面設計 、 包裝設計 、 圖標定制 、 用戶體驗 、交互設計、 網站建設 、平面設計服務

          日歷

          鏈接

          個人資料

          藍藍設計的小編 http://www.syprn.cn

          存檔

          亚洲va欧美va天堂v国产综合