《ReactNative》之IOS原生集成ReactNative

1.安装JavaScript依赖包

用终端进入到IOS原生项目根目录下,创建package.json文件(输入touch package.json)

打开package.json文件,在文件中写入以下内容:

{
  "name": "MyReactNativeApp",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start"
  },
  "dependencies": {
    "react": "16.0.0-alpha.6",
    "react-native": "0.44.3"
  }
}
    接下来使用npm(node包管理器,Node package manager)来安装React和React Native模块。 请打开一个终端/命令提示行,进入到项目目录中(即包含有package.json文件的目录),然后运行下列命令来安装:
$ npm install

2.安装CocoaPods

CocoaPods是针对iOS和Mac开发的包管理工具。我们用它来把React Native框架的代码下载下来并添加到你当前的项目中。 我们建议使用Homebrew来安装CocoaPods。
$ brew install cocoapods

3.配置CocoaPods的依赖

    React Native框架整体是作为node模块安装到项目中的。下一步我们需要在CocoaPods的Podfile中指定我们所需要使用的组件。
    在你开始把React Native集成到你的应用中之前,首先要决定具体整合的是React Native框架中的哪些部分。而这就是subspec要做的工作。在创建Podfile文件的时候,需要指定具体安装哪些React Native的依赖库。所指定的每一个库就称为一个subspec。
    可用的subspec都列在node_modules/react-native/React.podspec中,基本都是按其功能命名的。一般来说你首先需要添加Core,这一subspec包含了必须的AppRegistry、StyleSheet、View以及其他的一些React Native核心库。如果你想使用React Native的Text库(即<Text>组件),那就需要添加RCTText的subspec。同理,Image需要加入RCTImage,等等。
    我们需要在Podfile文件中指定所需的subspec。创建Podfile的最简单的方式就是在项目根目录中使用CocoaPods的init命令:
$ pod init
Podfile会创建在执行命令的目录中。你需要调整其内容以满足你的集成需求。调整后的Podfile的内容看起来类似下面这样:

platform :ios, '8.0' #手机的系统
target 'MyApp' do #工程名字
  pod 'React', :path => './node_modules/react-native', :subspecs => [
	'Core',
        'ART',
        'RCTActionSheet',
        'RCTGeolocation',
        'RCTImage',
        'RCTNetwork',
        'RCTPushNotification',
        'RCTSettings',
        'RCTText',
        'RCTVibration',
        'RCTWebSocket',
        'RCTLinkingIOS'
	# 在这里继续添加你所需要的RN模块
  ]
  
  # 如果你的RN版本 >= 0.42.0,则加入下面这行
  pod "Yoga", :path => "./node_modules/react-native/ReactCommon/yoga"
  target 'MyAppTests' do
    inherit! :search_paths
    # Pods for testing
  end

  target 'MyAppUITests' do
    inherit! :search_paths
    # Pods for testing
  end
end 

创建好了Podfile后,就可以开始安装React Native的pod包了。

$ pod install

注意:pod install的过程在国内非常不顺利,请自行配备稳定的翻墙工具,或是尝试一些镜像源。

出现如下信息代表安装成功

Analyzing dependencies
Fetching podspec for `React` from `./node_modules/react-native`
Fetching podspec for `Yoga` from `./node_modules/react-native/ReactCommon/yoga`
Downloading dependencies
Installing React (0.44.3)
Installing Yoga (0.44.3.React)
Generating Pods project
Integrating client project
Sending stats
Pod installation complete! There are 14 dependencies from the Podfile and 3 total pods installed.

4.创建index.ios.js文件(注意在0.49版本之后是index.js文件)

import React from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View
} from 'react-native';

class RNIndex extends React.Component {
  render() {
    
    return (
      <View style={styles.container}>
        <Text style={styles.text}>
          React Native 
        </Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#FFFFFF',
  },
  text: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
});

// 整体js模块的名称
AppRegistry.registerComponent('MyRNApp', () => RNIndex);

5.编写从原生界面进入RN界面的代码

注意引入 RCTRootView
在原生视图中编写一个按钮,用来跳转到RN界面
#import "ViewController.h"
#import <React/RCTRootView.h>

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    UIButton *btn = [[UIButton alloc] init];
    btn.frame = CGRectMake(50, 50,120, 30);
    btn.backgroundColor = [UIColor grayColor];
    [btn setTitle:@"ReactNative" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(enterRn:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
}
-(void)enterRn:(UIButton *) button{
    NSURL *jsCodeLocation = [NSURL URLWithString:@"http://127.0.0.1:8081/index.ios.bundle?platform=ios&dev=true"];
    //注意这里的 MyRNApp 必须对应“index.ios.js”中的“AppRegistry.registerComponent()”的第一个参数 
    RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation moduleName:@"MyRNApp" initialProperties:nil launchOptions:nil];
    rootView.backgroundColor = [UIColor colorWithRed:(36) green:(34) blue:(CGFloat)34 alpha:(1)];
    
    UIViewController *vc = [[UIViewController alloc] init];
    vc.view = rootView;
    
    [self presentViewController:vc animated:YES completion:nil];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end

6.添加App Transport Security例外

Apple现在默认会阻止读取不安全的HTTP链接。所以我们需要把本地运行的Packager服务添加到Info.plist的例外中,以便能正常访问Packager服务:
<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>localhost</key>
        <dict>
            <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
            <true/>
        </dict>
    </dict>
</dict>

7.测试集成结果

运行packager

在项目的根目录下输入 

npm start

然后再xcode中运行你的项目

注意,在用cocopods集成了ReactNative之后,从此之后应该打开 项目名称.xcworkspace文件以运行项目,而不是之前的项目名称.xcodeproj文件。




猜你喜欢

转载自blog.csdn.net/xukongjing1/article/details/80724272