现有iOS工程集成React Native

2,538 阅读3分钟

现有的iOS项目里集成RN的支持的大体框架, iOS应用集成RN的SDK,运行时加载预先打包好的jsBundle

主要内容

在现有iOS工程集成React Native组件的主要内容有:

  1. 设置React Native的依赖库和目录结构。
  2. 了解项目所需要的React Native组件。
  3. 使用CocoaPods 添加和管理这些组件。
  4. 使用JavaScript开发所需要的React Native组件。
  5. 添加React Native 组件的容器View - RCRootView
  6. 开启React Native服务器并运行本地工程。
  7. 验证React Native是否按预期工作。

前期准备

1. 设置目录结构

  • 创建React Native 工程的文件夹, 如: RNProject
  • 在React Native 工程文件夹RNProject中创建/ios文件夹。并将现有工程拷贝到/ios文件夹下。

2. 安装JavaScript依赖

在React Native 工程文件夹RNProject根目录创建package.json文件,文件的内容如下:

{
  "name": "MyReactNativeApp",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "yarn react-native start"
  }
}

打开终端,进入对应React Native工程目录, 安装下reactreact-native核心依赖

npm install react react-native

安装完成后,会在当前工程目录创建一个新的/node_modules文件夹, 这个文件里存储着当前工程所需的所有JavaScript依赖库。

最后,将node_modules/添加到iOS 工程的.gitignore文件中。

这阶段目录结构如下:

4BE36976-0C60-4F04-A3FF-8616D7356807.png

3. Install CocoaPods

CocoaPodsiOS开发的一个包管理工具. 请自行安装~。

添加React Native到App

1. 配置Cocoa Pods 依赖

进入React Native工程的ios目录,编辑Podfile文件(按照官网步骤可能会报错,因为react的版本不同,配置不同),内容如下👇🏻 参考链接

require_relative '../node_modules/react-native/scripts/react_native_pods'
require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules'

platform :ios, '10.0'

target 'RnDiffApp' do
  config = use_native_modules!

  use_react_native!(
    :path => config[:reactNativePath],
    # to enable hermes on iOS, change `false` to `true` and then install pods
    :hermes_enabled => false
  )

  target 'RnDiffAppTests' do
    inherit! :complete
    # Pods for testing
  end

  # Enables Flipper.
  #
  # Note that if you have use_frameworks! enabled, Flipper will not work and
  # you should disable the next line.
  use_flipper!()

  post_install do |installer|
    react_native_post_install(installer)
  end
end

编辑完成后,执行pod install命令。

2. 代码集成

1. 创建index.js文件

首先在React Native工程的根目录创建index.js文件,index.js是React Native应用程序的起点,一般来说是必须的。

2. 添加React Native代码到index.js中

打开index.js文件,将下面代码拷贝到其中。

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

class RNTest extends React.Component {
  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.title}>Hello</Text>
        <Image        
          style={styles.avatar}
          source={{uri: 'http:\/\/patpatwebstatic.s3.us-west-2.amazonaws.com\/origin\/other\/cms\/position\/60ab65d1b20a2.jpg'}}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    display: 'flex',
    alignItems: 'center',
    marginTop: 60
  },
  title: {
    fontSize: 20,
    textAlign: 'center',
    color: '#333'
  },
  avatar: {
    width: 300,
    height: 300,
    marginTop: 20
  }
});

// Module name
AppRegistry.registerComponent('RNTest', () => RNTest);

3. 使用RCTRootView加载显示index.js的内容

首先,在iOS文件中引入RCTRootView头文件

#import <React/RCTRootView.h>

创建一个点击事件,执行testRNButtonAction方法。

- (void)testRNButtonAction
{
        NSLog(@"RNTest Button Pressed");
        NSURL *jsCodeLocation = [NSURL URLWithString:@"http://localhost:8081/index.bundle?platform=ios"];

        RCTRootView *rootView =
        [[RCTRootView alloc] initWithBundleURL: jsCodeLocation
                                    moduleName: @"RNTest"
                             initialProperties:@{}
                                 launchOptions: nil];
        UIViewController *vc = [[UIViewController alloc] init];
        vc.view = rootView;
        [self presentViewController:vc animated:YES completion:nil];
 }

测试集成是否OK

1.添加应用程序运输安全异常

Apple已阻止隐式明码通讯 HTTP资源加载。 因此,需要在iOS工程的info.plist文件中做一下配置。

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>localhost</key>
        <dict>
            <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
            <true/>
        </dict>
    </dict>
</dict>

57CC240D-F388-437F-A4B5-2C465F829B9E.png

2.运行包

要运行app工程,首先要启动React Native的开发服务器。 在React Native工程的根目录运行:

npm start

启动成功如下:

image.png

如果报找不到yarn命令的错误,则需要安装一下yarn, 在终端输入命令:

npm install --global yarn

react native服务启动后,直接在Xcode中运行你的iOS工程,点击对应的按钮执行testRNButtonAction方法,成功加载React Native的界面。

image.png

另外,你还可以通过命令行的方式运行你的工程:

npx react-native run-ios

配置过程遇到的问题

  1. 找不到对应React Native依赖库问题: 如:No podspec found for FBReactNativeSpec in ../node_modules/react-native/Libraries/FBReactNativeSpec

  2. node 相关问题解决: blog.csdn.net/xinghuowuzh…

参考链接:

  1. Integration with Existing Apps