美文网首页
使用Cocoapods集成react native到原生项目

使用Cocoapods集成react native到原生项目

作者: 醉叶惜秋 | 来源:发表于2018-09-12 11:13 被阅读39次

对于react native(一下简称RCT)很多人应该都听说过,但真的集成使用,却遇到了太多坑,费了我好长的时间。网上找资料也看着乱的很,于是自己整理了一下:

在集成之前,你的电脑必须安装:

step 1.在项目中加入Cocoapods

Cocoapods是iOS中目前公认的最便捷,合理的第三方框架管理工具,具体的网上很多相关的文章,一搜就可以了。

项目工程根目录下
pod init
pod install

step 2.安装react-native

先创建一个文件夹用来存放react-native

mkdir react

进入创建的react文件中

cd react 
  • 创建package.json
{
  "name": "你的项目名",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start"
  },
  "dependencies": {  // 这里填入依赖项
    "react": "16.0.0",  // 其实 react也是作为一个第三方库存在的
    "react-native": "0.50"  // 这个也是 - - 依次可以加入很多第三方库,然后使用npm install初始化,其实这里和cocoapods很相似
  }
}

在react文件夹中安装react-native

npm install

创建index.js文件

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

class RNHighScores extends React.Component {
  render() {
    var contents = this.props["scores"].map(score => (
      <Text key={score.name}>
        {score.name}:{score.value}
        {"\n"}
      </Text>
    ));
    return (
      <View style={styles.container}>
        <Text style={styles.highScoresTitle}>2048 High Scores!</Text>
        <Text style={styles.scores}>{contents}</Text>
      </View>
    );
  }
}

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

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

step 3.使用Cocoapods集成react-native

在Podfile中添加React

pod 'React', :path => './react/node_modules/react-native', :subspecs => [
  'Core',
  'DevSupport',
  'RCTText',
  'RCTNetwork',
  'RCTWebSocket',
  'BatchedBridge',
  ]
  pod 'yoga', :path => './react/node_modules/react-native/ReactCommon/yoga'
# 根据需求添加项目中需要的模块

RNHighScores是整体 js 模块(即你所有的 js 代码)的名称。你在 iOS 原生代码中添加 React Native 视图时会用到这个名称。

掌握核心科技: RCTRootView

现在我们已经在index.js中创建了 React Native 组件,下一步就是把这个组件添加给一个新的或已有的ViewController

    1. Create an Event Path


      image.png
    1. 事件处理
      首先导入RCTRootView的头文件。
#import <React/RCTRootView.h>

这里的initialProperties注入了一些演示用的数据。在 React Native 的根组件中,我们可以使用this.props来获取到这些数据。

- (IBAction)highScoreButtonPressed:(id)sender {
    NSLog(@"High Score Button Pressed");
    NSURL *jsCodeLocation = [NSURL URLWithString:@"http://localhost:8081/index.bundle?platform=ios"];

    RCTRootView *rootView =
      [[RCTRootView alloc] initWithBundleURL: jsCodeLocation
                                  moduleName: @"RNHighScores"
                           initialProperties:
                             @{
                               @"scores" : @[
                                 @{
                                   @"name" : @"Alex",
                                   @"value": @"42"
                                  },
                                 @{
                                   @"name" : @"Joel",
                                   @"value": @"10"
                                 }
                               ]
                             }
                               launchOptions: nil];
    UIViewController *vc = [[UIViewController alloc] init];
    vc.view = rootView;
    [self presentViewController:vc animated:YES completion:nil];

测试集成结果

    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>

App Transport Security 对于用户来说是有利的。所以最好记得在发布之前重新启用这些安全限制。

  1. 运行 Packager

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

$ npm start
  1. 运行应用
    如果你使用的是 Xcode,那么照常编译和运行应用即可。如果你没有使用 Xcode(但是你仍然必须安装 Xcode),则可以在命令行中使用以下命令来运行应用:
# 在项目的根目录中执行:
$ react-native run-ios
image.png

相关文章

网友评论

      本文标题:使用Cocoapods集成react native到原生项目

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