六月伊人,国产精品制服丝袜欧美,亚洲va在线∨a天堂va欧美va,精品亚洲一区二区三区在线观看国产老熟女色视频,国产熟女九色,国产又粗又大,久久人人网国产精品

React Native原生與JS層交互

2018-7-2    seo達(dá)人

如果您想訂閱本博客內(nèi)容,每天自動(dòng)發(fā)到您的郵箱中, 請點(diǎn)這里

最近在對《React Native移動(dòng)開發(fā)實(shí)戰(zhàn)》一書進(jìn)行部分修訂和升級。在React Native開發(fā)中,免不了會(huì)涉及到原生代碼與JS層的消息傳遞等問題,那么React Native究竟是如何實(shí)現(xiàn)與原生的互相操作的呢?

原生給React Native傳參

原生給React Native傳值

原生給JS傳值,主要依靠屬性,也就是通過initialProperties,這個(gè)RCTRootView的初始化函數(shù)的參數(shù)來完成。通過RCTRootView的初始化函數(shù)你可以將任意屬性傳遞給React Native應(yīng)用,參數(shù)initialProperties必須是NSDictionary的一個(gè)實(shí)例。RCTRootView有一個(gè)appProperties屬性,修改這個(gè)屬性,JS端會(huì)調(diào)用相應(yīng)的渲染方法。

使用RCTRootView將React Natvie視圖封裝到原生組件中。RCTRootView是一個(gè)UIView容器,承載著React Native應(yīng)用。同時(shí)它也提供了一個(gè)聯(lián)通原生端和被托管端的接口。

例如有下面一段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中關(guān)于initialProperties的名字叫什么,在JS中都是this.props開頭,然后接下來才是key名字。

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

使用appProperties進(jìn)行參數(shù)傳遞

RCTRootView同樣提供了一個(gè)可讀寫的屬性appProperties。在appProperties設(shè)置之后,React Native應(yīng)用將會(huì)根據(jù)新的屬性重新渲染。當(dāng)然,只有在新屬性和舊的屬性有更改時(shí)更新才會(huì)被觸發(fā)。

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

可以隨時(shí)更新屬性,但是更新必須在主線程中進(jìn)行,讀取則可以在任何線程中進(jìn)行。

React Native執(zhí)行原生方法及回調(diào)

React Native執(zhí)行原生方法

.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

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

并且必須明確的聲明要給Javascript導(dǎo)出的方法,否則React Native不會(huì)導(dǎo)出任何方法。OC中聲明要給Javascript導(dǎo)出的方法,通過RCT_EXPORT_METHOD()宏來實(shí)現(xiàn)。

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}
      >點(diǎn)擊 </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則要引入相應(yīng)的命名空間import { NativeModules } from ‘react-native’;然后再進(jìn)行調(diào)用CalendarManager.doSomething(‘sdfsdf’,’sdfsdfs’);橋接到Javascript的方法返回值類型必須是void。React Native的橋接操作是異步的,所以要返回結(jié)果給Javascript,你必須通過回調(diào)或者觸發(fā)事件來進(jìn)行。

傳參并回調(diào)

RCT_EXPORT_METHOD(testCallbackEvent:(NSDictionary *)dictionary callback:(RCTResponseSenderBlock)callback)
{ NSLog(@"當(dāng)前名字為:%@",dictionary); NSArray *events=@[@"callback ", @"test ", @" array"];
  callback(@[[NSNull null],events]);
}
    
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

說明:第一個(gè)參數(shù)代表從JavaScript傳過來的數(shù)據(jù),第二個(gè)參數(shù)是回調(diào)方法; 
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}
      >點(diǎn)擊 </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

參數(shù)類型說明

RCT_EXPORT_METHOD 支持所有標(biāo)準(zhǔn)JSON類型,包括:

  • string (NSString)
  • number (NSInteger, float, double, CGFloat, NSNumber)
  • boolean (BOOL, NSNumber)
  • array (NSArray) 包含本列表中任意類型
  • object (NSDictionary) 包含string類型的鍵和本列表中任意類型的值
  • function (RCTResponseSenderBlock)

除此以外,任何RCTConvert類支持的的類型也都可以使用(參見RCTConvert了解更多信息)。RCTConvert還提供了一系列輔助函數(shù),用來接收一個(gè)JSON值并轉(zhuǎn)換到原生Objective-C類型或類。例如:

#import "RCTConvert.h" #import "RCTBridge.h" #import "RCTEventDispatcher.h" //  對外提供調(diào)用方法,為了演示事件傳入屬性字段 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原生方法發(fā)送數(shù)據(jù)到JavaScript中,那么使用eventDispatcher。例如:

#import "RCTBridge.h" #import "RCTEventDispatcher.h" @implementation CalendarManager @synthesize bridge = _bridge; //  進(jìn)行設(shè)置發(fā)送事件通知給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函數(shù)中取消事件的訂閱。

import { NativeAppEventEmitter } from 'react-native';

var subscription = NativeAppEventEmitter.addListener( 'EventReminder',
  (reminder) => console.log(reminder.name)
); ... // 千萬不要忘記忘記取消訂閱, 通常在componentWillUnmount函數(shù)中實(shí)現(xiàn)。
subscription.remove();
    
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

用NativeAppEventEmitter.addListener中注冊一個(gè)通知,之后再OC中通過bridge.eventDispatcher sendAppEventWithName發(fā)送一個(gè)通知,這樣就形成了調(diào)用關(guān)系。

藍(lán)藍(lán)設(shè)計(jì)m.wnxcall.com )是一家專注而深入的界面設(shè)計(jì)公司,為期望卓越的國內(nèi)外企業(yè)提供卓越的UI界面設(shè)計(jì)、BS界面設(shè)計(jì) 、 cs界面設(shè)計(jì) 、 ipad界面設(shè)計(jì) 、 包裝設(shè)計(jì) 、 圖標(biāo)定制 、 用戶體驗(yàn) 、交互設(shè)計(jì)、 網(wǎng)站建設(shè) 、平面設(shè)計(jì)服務(wù)

分享本文至:

日歷

鏈接

個(gè)人資料

存檔