React Native - 构建 Native Module 图示指南

前端之家收集整理的这篇文章主要介绍了React Native - 构建 Native Module 图示指南前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

React Native 支持使用 Java 或者 Objective-C 来构建本地的模块,并和 JS 通信,从而在 JS 中,可以调用模块中的函数,并得到结果。

对于如何构建 Native Module,官方文档以及给了详细的说明,这里只是以图解的方式讲述如何操作。

iOS 部分

第一步,打开 Xcode,并选择新建项目,请选择 Cocoa Touch static library :

第二步,输入项目的名字等,并保存:

第三步,如果你的代码需要任何一种库,请选择库:

然后,开始书写你的代码

在头文件里面,加入 FB 提供的库的头文件,并指派类支持它:

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

回到 MyComponent.m,加入

  1. #import "MyComponent.h"
  2.  
  3. @implementation MyComponent
  4.  
  5. // 告诉 RN,在 JS 中访问此 Native Module 的时候,使用 NativeModules.MyComponent 的名字
  6. RCT_EXPORT_MODULE();
  7.  
  8. @end

最后,加入,要提供给 JS 调用方法,这里支持两种调用模式,一种是同步的调用,此方法将运行与 JS 的线程之中,并阻塞当前的操作,直到完成,如下:

  1. RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(helloSync:(NSString *)greeting)
  2. {
  3. // RCTLogInfo(@" %@",greeting);
  4. return @"Hi I am here";
  5. }

另一种是,异步的调用,线程将在 RN 指派的线程队列执行,使用 Promise 返回结果,如下:

  1. RCT_EXPORT_METHOD(hello:(NSString *)greeting resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject)
  2. {
  3. if ([greeting isEqualToString: @""]) {
  4. NSError *error = [NSError errorWithDomain:@"example" code:200 userInfo: nil];
  5. reject(@"",@"",error);
  6. return;
  7. }
  8.  
  9. resolve(@"Hi,I am here");
  10. }

最后,使用 JS 在 RN 中调用它们:

  1. import { NativeModules } from 'react-native';
  2.  
  3. const MyComponent = NativeModules.MyComponent;
  4.  
  5. const reply = MyComponent.helloSync ('Hi');
  6. console.log(reply);
  7.  
  8. // 调用异步方法
  9. MyComponent.hello ('Hi').then ((reply) => {
  10. console.log(reply);
  11. }).catch (err => console.log(err));

剩下的就是加入你的 RN 项目,如下:

先使用 npm 创建一个本地的PKG。

  1. mkdir MyComponent
  2. cd MyComponent
  3. npm init

给一个包的名字,叫做 react-native-mycomponent-example 好了。

然后,在你的 RN 项目的 package.json 的依赖部分中,使用 local path,如下:

  1. "react-native-mycomponent-example": "file: ./MyComponent"

注意,file 后面是你存放自己的 component 的文件夹。

然后,安装并链接,如下:

  1. npm install react-native-mycomponent-example
  2. react-native link react-native-mycomponent-example

开始使用吧!你并不需要发布你的组件,使用 local path 是一种访问本地组件的简单方法

相当容易,这样你可以把 JS 中无法完成或者是性能低的代码放到 Native Module 里面完成。

Android / Java 部分

Android 部分更加简单,如果你用的是 Android Studio

这篇文章很详细,

http://www.liuchungui.com/blog/2016/05/08/reactnativezhi-yuan-sheng-mo-kuai-kai-fa-bing-fa-bu-androidpian/

猜你在找的React相关文章