首先在React Native中文网
https://reactnative.cn/docs/getting-started/搭建运行环境
将React Native集成到现有的iOS应用中需要如下几个主要步骤:
1.搭建运行环境
基本步骤 与中文网一致,大致分为这几步:
a.首先安装使用Homebrew
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
b.其次 来安装 Node 和 Watchman。在命令行中执行下列命令安装:
brew install node
brew install watchman
c.如果你已经安装了 Node,请检查其版本是否在 v10 以上。安装完 Node 后建议设置 npm 镜像以加速后面的过程(或使用科学上网工具)。
注意:不要使用 cnpm!cnpm 安装的模块路径比较奇怪,packager 不能正常识别!
npm config set registry https://registry.npm.taobao.org --global
npm config set disturl https://npm.taobao.org/dist --global
1.1Yarn、React Native 的命令行工具(react-native-cli)
Yarn是 Facebook 提供的替代 npm 的工具,可以加速 node 模块的下载。React Native 的命令行工具用于执行创建、初始化、更新项目、运行打包服务(packager)等任务。
npm install -g yarn react-native-cli
安装完 yarn 后同理也要设置镜像源:
yarn config set registry https://registry.npm.taobao.org --global yarn config set disturl https://npm.taobao.org/dist --global
安装完 yarn 之后就可以用 yarn 代替 npm 了,例如用yarn
代替npm install
命令,用yarn add 某第三方库名
代替npm install 某第三方库名
。
1.2Xcode
React Native 目前需要Xcode 9.4 或更高版本。你可以通过 App Store 或是到Apple 开发者官网上下载。这一步骤会同时安装 Xcode IDE、Xcode 的命令行工具和 iOS 模拟器。
启动 Xcode,并在Xcode | Preferences | Locations
菜单中检查一下是否装有某个版本的Command Line Tools
。Xcode 的命令行工具中包含一些必须的工具,比如git
等。
2. 创建一个React Native项目
- 首先,你需要有一个React Native项目;
- 为已存在的iOS应用添加React Native所需要的依赖(CocoaPods);
- 创建index.js并添加你的React Native代码;
- 创建一个ViewController来承载React Native,在这个ViewController中创建一个RCTRootView来作为React Native服务的容器;
- 启动React Native的Packager服务,运行应用;
- (可选)根据需要添加更多React Native的组件;
- 运行、调试、打包、发布应用;
- 升职加薪、迎娶白富美,走向人生巅峰!;
2.1 通过react-native init
命令来初始化一个React Native项目。
在新建的文件目录ReactNative里执行
react-native init RNHybrid
上述命令会初始化一个完成的名为RNHybrid的React Native项目,然后我们将里面的android
和ios
目录删除,替换成已存在Android和iOS项目。
2.2. 添加React Native所需要的依赖
在上文中我们已经创建了个一个React Native项目,接下来我们来看一下如何将这个React Native项目和我们已经存在的Native项目进行融合。
在进行融合之前我们需要将已经存在的Native项目放到我们创建的RNHybrid下,比如:我有一个名为RNHybrid
的iOS项目,将其放到RNHybrid目录下:
RNHybrid
├── RNHybridiOS
├── package.json
├── node_modules
└── .gitignore
2.3配置CocoaPods依赖
接下来我们需要为已经存在的RNHybridiOS项目添加 React Native依赖,在RNHybridiOS目录下创建一个Podfile
文件(如果已经添加过可跳过):
pod install
然后,vim podfile 我们在Podfile
文件中添加如下代码:
target 'RNHybridiOS' do
# Uncomment the next line if you're using Swift or would like to use dynamic frameworks
# use_frameworks!
# Your 'node_modules' directory is probably in the root of your project,
# but if not, adjust the `:path` accordingly
pod 'React', :path => '../node_modules/react-native', :subspecs => [
'Core',
'CxxBridge', # Include this for RN >= 0.47
'DevSupport', # Include this to enable In-App Devmenu if RN >= 0.43
'RCTText',
'RCTNetwork',
'RCTWebSocket', # Needed for debugging
'RCTAnimation', # Needed for FlatList and animations running on native UI thread
# Add any other subspecs you want to use in your project
]
# Explicitly include Yoga if you are using RN >= 0.42.0
pod 'yoga', :path => '../node_modules/react-native/ReactCommon/yoga'
# Third party deps podspec link
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
其中target是你原来应用的项目名字
接下来在RNHybridiOS
目录下执行:
pod install
执行成功之后,你会看到如下输出:
如果:出现 Unable to find a specification for 'boost-for-react-native' depended upon by Folly
的错误,则需要在目录下执行pod update
即可 。
3.设置App Transport Security Settings
由于我们的RNHybridiOS
应用需要加载本地服务器上的JS Bundle,而且是http的协议传输,所以需要设置App Transport Security Settings
,让其支持http传输,否则会出现如下错误:
由于App Transport Security Settings
网上设置的教程有很多,在这里就不重复了,需要的同学可以Google一下xcode http。
此过程所遇到的更多问题可查阅:React Native与iOS 混合开发讲解的视频教程
4.创建index.js并添加你的React Native代码
通过上述两步,我们已经为RNHybridiOS项目添加了React Native依赖,接下来我们来开发一些JS代码。
在RNHybrid目录下创建一个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);
RNHighScores
是整体 js 模块(即你所有的 js 代码)的名称。你在 iOS 原生代码中添加 React Native 视图时会用到这个名称。
另外,在上述代码中我们引用了一个App.js
文件:
这个App.js
文件代表了我们React Native的一个页面,在这个页面中显示了this is App
的文本内容。
以上就是为本次演示所添加的React Native代码,你也可以根据需要添加更多的React Native代码以及组件出来。此过程更细致的讲解可查阅:React Native与iOS 混合开发讲解的视频教程
5. 为React Native创建一个ViewController和RCTRootView来作为容器
经过上述步骤,我们已经为RNHybrid项目添加了React Native依赖,并且创建一些React Native代码和注册了一个名为App1
的组件,接下来我们来学习下如何在RNHybridiOS项目中使用这个App1
组件。
5.1创建RNPageController
首先我们需要创建一个ViewController和RCTRootView来作为React Native的容器。
首先导入 RCTRootView的头文件
#import <React/RCTRootView.h>
- (viod)start {
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];
}
参数说明
initWithBundleURL
:用于设置jsCodeLocation
,有上述三种设置方式,在开发阶段推荐使用RCTBundleURLProvider
的形式生成jsCodeLocation
,release只会使用静态js bundle;moduleName
:用于指定RN要加载的JS 模块名,也就是上文中所讲的在index.js
中注册的模块名;launchOptions
:主要在AppDelegate加载JS Bundle时使用,这里传nil就行;initialProperties
:接受一个NSDictionary
类型的参数来作为RN初始化时传递给JS的初始化数据
5.2 运行React Native
经过上述的步骤,我们已经完成了对一个现有iOS项目RNHybrid添加了RN,并且创建了一个RNPageController
来加载我们在JS中注册的名为App1
的RN 组件。
接下来我们来启动RN服务器,运行RNHybridiOS项目打开RNPageController
来查看效果:
$ npm start
在RNHybrid
的根目录运行上述命令,来启动一个RN本地服务:
然后我们打开Xcode,点击运行按钮或者通过快捷键Command+R
来将RNHybridiOS
安装到模拟器上:
6. 添加更多React Native的组件
我们可以根据需要添加更多的React Native的组件:
import { AppRegistry } from 'react-native';
import App from './App';
import App2 from './App2';
AppRegistry.registerComponent('App1', () => App);
AppRegistry.registerComponent('App2', () => App);
然后,在Native中根据需要加载指定名字的RN组件即可。
7. 调试、打包、发布应用
7.1调试
调试这种混合的RN应用和调试一个纯RN应用时一样的,都是Command + D
打开RN 开发者菜单
,Command + R
进行reload JS,另外大家也可以通过学习课程来掌握更多RN调试的技巧。
7.2打包
虽让,通过上述步骤,我们将RN和我们的RNHybridiOS项目做了融合,但打包RNHybridiOS你会发现里面并不包含JS部分的代码,如果要将JS代码打包进iOS ipa包中,可以通过如下命令:
react-native bundle --entry-file index.js --platform ios --dev false --bundle-output release_ios/main.jsbundle --assets-dest release_ios/
记得在运行上述命令之前先创建一个release_ios
目录。
参数说明
--platform ios
:代表打包导出的平台为iOS;--dev false
:代表关闭JS的开发者模式;-entry-file index.js
:代表js的入口文件为index.js
;--bundle-output
:后面跟的是打包后将JS bundle包导出到的位置;--assets-dest
:后面跟的是打包后的一些资源文件导出到的位置;
上述命令执行完成之后,会在release_ios
目录下生成main.jsbundle
,main.jsbundle.meta
,以及assets
目录(如果RN中用到了一些图片资源的话)。
将js bundle包和图片资源导入到iOS项目中
这一步我们需要用到XCode,选择assets文件夹与main.jsbundle文件将其拖拽到XCode的项目导航面板中即可。
然后,修改jsCodeLocation
,添加如下代码:
...
NSURL *jsCodeLocation;http://coding.imooc.com/class/304.html
//jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
+jsCodeLocation = [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
上述代码的作用是让React Native去使用我们刚才导入的jsbundle,这样以来我们就摆脱了对本地nodejs服务器的依赖。
提示:如果在项目中使用了CodePush热更新,那么我们需要就可以直接通过CodePush来读取本地的jsbundle,方法如下:
到目前为止呢,我们已经将js bundle包和图片资源导入到iOS项目中,接下来我们就可以发布我们的iOS应用了。
8 发布iOS应用
发布iOS应用我们需要有一个99美元的账号用于将App上传到AppStore,或者是299美元的企业级账号用于将App发布到自己公司的服务器或第三方公司的服务器。
接下来我们就需要进行申请APPID 在Tunes Connect创建应用 打包程序 将应用提交到app store等几大步骤。
因为官方文档中有详细的说明,在这我就不再重复了。