React Native集成到IOS原生项目

来源:互联网 发布:怎样安装ps软件 编辑:程序博客网 时间:2024/06/05 02:16

这里默认电脑上已经安装了cocoapods和React-Native,如果没有RN开发环境,可以点击这里按照步骤配置。


0、新建项目

首先,先使用xcode新建一个项目,然后在项目的根目录下新建一个文件夹,用于存放RN的组件库还有其他一些文件。这里假设新建一个名为 RNComponent 的文件夹。目录结构为:

示图

1、新建RN配置文件

准备妥当以后,我们在 RNComponent 这个文件夹里就可以放置所有RN相关的文件。新建一个用户初始化RN的配置文件,是Json文件。命名为 package.json

示图

内容为:

{  "name": "RNApp",  "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.0",    "react-native-deprecated-custom-components": "^0.1.0",    "react-native-tab-navigator": "^0.3.3"  }}

上述代码里的配置信息已经足够现在集成项目使用,如果需要了解其它配置信息的话,可以参考下方:

  • name 是指RN项目的名字,这个和原生项目的名字保持一致即可
  • version 是指项目版本号
  • description 项目的描述
  • author 开发者个人信息
  • private 当设置为true时,npm不会发布这个package
  • dependencies 指需要哪些依赖组件,并且指明版本号,这样用户安装时,会自动安装这些依赖组件
  • devDependencies 是指开发或测试的依赖组件,正式打包的时候不会打包到最终的生产包中
  • scripts 定义npm脚本命令,key值表示命令名,value值表示命令对应的脚本或者脚本路径
  • main 工程生成的package主入口点,当在 node 中调用 require(‘{module name}’) 时会 require 到这个文件
  • repostitory 如果我们这个工程是开源的,这个字段用来指明工程的仓库 URL 地址以及版本控制系统的类型,这可以方便其他开发者贡献代码
  • bugs 使用者可以提交bugs的 URL 或者邮件地址

文章结尾放了一些 package.json 的扩展内容,感兴趣的可以看看。

2、安装RN

编辑好 package.json 以后,我们来安装RN。这里需要确定当前目录是否为刚才新建的目录,并且确定 package.json 存在,然后,输入安装RN,在终端输入命令 npm install

示图

当出现下图,就说明安装成功,并且目录里多了一个 node_modules 文件夹。如图:

示图

示图

3、设置podfile文件

安装完毕以后,我们切换到xcode项目根目录中,然后再终端输入 pod init 命令,来生成podfile文件。如图:

示图

示图

4、使用pod管理依赖组件

生成 podfile 文件以后,直接编辑,编辑信息如下:

pod 'Yoga',  :path => './RNComponent/node_modules/react-native/ReactCommon/yoga'  pod 'React', :path => ‘./RNComponent/node_modules/react-native/', :subspecs => [ 'Core',  'ART',  'RCTActionSheet',  'RCTAdSupport',  'RCTGeolocation',  'RCTImage',  'RCTNetwork',  'RCTPushNotification',  'RCTSettings',  'RCTText',  'RCTVibration',  'RCTWebSocket',  'RCTLinkingIOS']

这里把所有组件全部做了依赖管理,所以在开发中,就需要根据实际需求来做对应的依赖。如果路径没有指定正确,就会报错,具体点击这里参考。

编辑好以后,直接在终端输入 pod install 命令,安装依赖。出现下图时,就说明安装成功:

示图

此时目录结构为:

示图

5、新建RN项目js文件入口

接下来需要在 RNComponent 文件夹中新建RN的js入口文件 index.ios.js ,这里直接复制RN初始化时的文件,内容如下:

/** * Sample React Native App * https://github.com/facebook/react-native * @flow */import React, { Component } from 'react';import {  AppRegistry,  //注册  StyleSheet,   //样式  Text,         //文本组件  View,          //视图组件  Image} from 'react-native';export default class RNApp extends Component {    render() {        return (            <View style={styles.container}>              <Text style={styles.welcome}>                nethanhan              </Text>              <Text style={styles.instructions}>                To get started, edit index.ios.js              </Text>              <Text style={styles.instructions}>                Press Cmd+R to reload,{'\n'}                Cmd+D or shake for dev menu              </Text>            </View>        );    }}const styles = StyleSheet.create({  container: {    flex: 1,    justifyContent: 'center',    alignItems: 'center',    backgroundColor: '#F5FCFF',  },  welcome: {    fontSize: 20,    textAlign: 'center',    margin: 10,  },  instructions: {    textAlign: 'center',    color: '#333333',    marginBottom: 5,  },});//注意这里的名字需要和项目名字一致AppRegistry.registerComponent('RNApp', () => RNApp);

6、集成测试

完成所有工作以后,我们打开xcode项目,然后创建一个按钮,用于跳转到另外一个控制器,然后这个控制器直接把RN界面当成自己的view来展示。如图:

示图

RN模块的类是 RCTRootView ,实例化时需要传入相应的参数:

示图

然后在项目的plist文件中添加允许http连接声明,代码如下:

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

接下来在终端中切换到刚才的 RNCompoent 目录下,运行 react-native start 命令,如图:

示图

最后运行xcode项目,点击按钮,会跳转到RN界面的控制器里,就会出现RN的界面(第一次运行会慢一些),如图:

示图

OK! 至此,我们已经成功的把RN集成到IOS原生项目中。 如果有什么疑问,随时欢迎评论!

7、package.json扩展

我们在上方 package.json 中只配置了一些常用的信息,还有一些其它的说明,可以点击这里查阅。因为是属于npm的知识点,所以在这里放上一个真实项目的 package.json 的内容:

{  "name": "module-name",  "version": "10.3.1",  "description": "An example module to illustrate the usage of a package.json",  "author": "Your Name <you.name@example.org>",  "contributors": [{  "name": "Foo Bar",  "email": "foo.bar@example.com"}],  "bin": {  "module-name": "./bin/module-name"},  "scripts": {    "test": "vows --spec --isolate",    "start": "node index.js",    "predeploy": "echo im about to deploy",    "postdeploy": "echo ive deployed",    "prepublish": "coffee --bare --compile --output lib/foo src/foo/*.coffee"  },  "main": "lib/foo.js",  "repository": {  "type": "git",  "url": "https://github.com/nodejitsu/browsenpm.org"},  "bugs": {  "url": "https://github.com/nodejitsu/browsenpm.org/issues"},  "keywords": [  "nodejitsu",  "example",  "browsenpm"],  "dependencies": {    "primus": "*",    "async": "~0.8.0",    "express": "4.2.x",    "winston": "git://github.com/flatiron/winston#master",    "bigpipe": "bigpipe/pagelet",    "plates": "https://github.com/flatiron/plates/tarball/master"  },  "devDependencies": {    "vows": "^0.7.0",    "assume": "<1.0.0 || >=2.3.1 <2.4.5 || >=2.5.2 <3.0.0",    "pre-commit": "*"  },  "preferGlobal": true,  "private": true,  "publishConfig": {  "registry": "https://your-private-hosted-npm.registry.nodejitsu.com"},  "subdomain": "foobar",  "analyze": true,  "license": "MIT"}