美文网首页RN学习日志
RN - 集成到现有原生应用

RN - 集成到现有原生应用

作者: Joh蜗牛 | 来源:发表于2019-03-11 18:23 被阅读6次

附上官方文档:
https://reactnative.cn/docs/integration-with-existing-apps/

一、开发环境准备

1.配置项目目录结构

新建一个空文件夹,在内部建一个名为“ios”的文件夹,然后将已有的iOS原生项目报备至“ios”文件夹中,如图:


原生项目内容放入ios内
2.安装JavaScript依赖包

1)在项目根目录下创建一个名为“package.json”的空文本文件,填入一下内容:

{
  "name": "MyReactNativeApp", //--- 改为自己的项目名称
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start"
  }
}

2)接下来打开终端,进入项目目录中(cd至根目录),然后运行一下命令来安装:

yarn add react-native

3)若顺利的话,可看到以下信息:

warning "react-native@0.52.2" has unmet peer dependency "react@16.6.3".

这是正常现象,意味着我们还需要安装指定版本的 React:

yarn add react@16.6.3

注意必须严格匹配警告信息中所列出的版本,高了或者低了都不可以。

坑:

安装过程中,在进行了(2)操作之后,出现了以下提示:

command not found

憋害怕,在这里添加一个步骤即可--在操作(2)之前,先输入此行命令:

yarn

操作完之后接着进行操作(2),完美解决问题~~

3.安装CocoaPods

这里我们使用Homebrew来安装CocoaPods:

brew install cocoapods

二、把 React Native 添加到你的应用中

1.Xcode命令行工具

打开Xcode,点击快捷按钮“command+,”打开设置,选择位置面板,在“命令行工具”下拉列表中选择最新版本来安装工具。


选择最新版本哦
2.配置CocoaPods的依赖

我们需要在Podfile文件中指定所需的subspec。
创建Podfile的最简单的方式就是在/ios子目录中使用 CocoaPods 的init命令:
打开终端,先cd至ios文件夹,然后输入:

pod init

Podfile会创建在执行命令的目录中。你需要调整其内容以满足你的集成需求。调整后的Podfile的内容看起来类似下面这样:

# target的名字一般与你的项目名字相同
target 'NumberTileGame' do

  # 'node_modules'目录一般位于根目录中
  # 但是如果你的结构不同,那你就要根据实际路径修改下面的`:path`
  pod 'React', :path => '../node_modules/react-native', :subspecs => [
    'Core',
    'CxxBridge', # 如果RN版本 >= 0.47则加入此行
    'DevSupport', # 如果RN版本 >= 0.43,则需要加入此行才能开启开发者菜单
    'RCTText',
    'RCTNetwork',
    'RCTWebSocket', # 调试功能需要此模块
    'RCTAnimation', # FlatList和原生动画功能需要此模块
    # 在这里继续添加你所需要的其他RN模块
  ]
  # 如果你的RN版本 >= 0.42.0,则加入下面这行
  pod 'yoga', :path => '../node_modules/react-native/ReactCommon/yoga'

  # 如果RN版本 >= 0.45则加入下面三个第三方编译依赖
  pod 'DoubleConversion', :podspec => '../node_modules/react-native/third-party-podspecs/DoubleConversion.podspec'
  pod 'glog', :podspec => '../node_modules/react-native/third-party-podspecs/glog.podspec'
  pod 'Folly', :podspec => '../node_modules/react-native/third-party-podspecs/Folly.podspec'

end

创建好了Podfile后,就可以开始安装 React Native 的 pod 包了,使用如下命令:

pod install

坑:本人项目中,由于版本号过低导致此步骤一直报错,由8.0改为9.0之后,就解决了此问题。(仅支持9.0及以上)

坑啊,大家注意啊
3.代码集成

1.在项目根目录下创建一个index.js文件。(注意在 0.49 版本之前是 index.ios.js 文件)
2.添加自己的React Native 代码
在index.js中编写代码(一下仅仅是示例):

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

class RNHighScores extends React.Component {
    render() {

        return (
                <View style={styles.container}>
                <Text style={styles.highScoresTitle}>恭喜你,集成成功!</Text>
                </View>
                );
    }
}

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

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

3.原生页面关联
我们已经在index.js中创建了 React Native 组件,下一步就是把这个组件添加给一个新的或已有的ViewController
可以在Xcode项目中,新建一个页面,此页面即使用RN所开发的页面:

//
//  SalesReportRNViewController.m
//

#import "SalesReportRNViewController.h"
#import <React/RCTRootView.h>

@interface SalesReportRNViewController ()

@end

@implementation SalesReportRNViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.title = @"React Native";

    NSURL *jsCodeLocation = [NSURL URLWithString:@"http://localhost:8081/index.bundle?platform=ios"];

    RCTRootView *rootView =
    [[RCTRootView alloc] initWithBundleURL: jsCodeLocation
                                moduleName: @"RNHighScores"
                         initialProperties:nil
                             launchOptions: nil];

    self.view = rootView;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


4.测试集成结果

1.添加 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>
效果图

2.运行Packager
要运行应用,首先需要启动开发服务器(即 Packager,它负责实时监测 js 文件的变动并实时打包,输出给客户端运行)。具体只需简单进入到项目根目录中,然后运行:

npm start

坑:每次打开项目之前都要运行!!!

3.打开iOS项目,运行Xcode,跳转至该页面,如下:


恭喜你,集成成功!

4.大功告成,现在你可以在index.js中编写页面了

相关文章

网友评论

    本文标题:RN - 集成到现有原生应用

    本文链接:https://www.haomeiwen.com/subject/yshbuqtx.html