使用Cocoapods为现有iOS原生项目集成React Nat
2016-11-02 本文已影响0人
一直搬着砖
1、安装ReactNative环境
这一步可以参照 http://reactnative.cn/docs/0.36/getting-started.html#content
2、在现有的项目目录下运行 react-native init 目录名称
。
这里的目录名称在后面Cocoapods 链接时会用到。
3、使用Cocoapods管理项目
1. pod init
2. pod install
4、在Podfile 文件中添加
pod 'React', :path => './Test/node_modules/react-native', :subspecs => [
'Core',
'RCTText',
'RCTImage',
'RCTActionSheet',
'RCTGeolocation',
'RCTNetwork',
'RCTSettings',
'RCTVibration',
'RCTWebSocket',
]
其中的Test就是第二步中的目录名称。
5 、在你的项目的任意ViewController中添加以下代码
NSURL *jsCodeLocation = [NSURL URLWithString:@"http://localhost:8081/index.ios.bundle?platform=ios"];
RCTRootView * rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
moduleName:@"Test"
initialProperties:nil
launchOptions:nil];
[self.view addSubview:rootView];
其中的moduleName的值需要再 index.ios.js 中注册,类似
AppRegistry.registerComponent('Test', () => Test);
6、 在第二步中目录下面的node_modules目录下,运行 npm start
然后运行你的项目就可以看到下面的界面。

至此,就在原来的项目中添加了ReactNative模块。
可能遇到的问题。
如果报错 Native module cannot be null,那么就是Cocoapods中依赖的库没有添加完全。在上面的第四步中,已经加了需要使用的基本库,所以,应该不会报以下错误。

因为你的服务是在电脑上启动的,所以可能会出现找不到服务器的错误,那么修改代码中的localhost为你电脑的IP地址即可,如果使用的是局域网地址,在真机上运行的话,那么你的手机应该和电脑处于同一个局域网内。
如果遇到以下错误:
[!] Unable to find a specification for yoga (= 0.54.2.React)
depended upon by React/Core
根据提示需要添加yoga,所以在pod文件里添加pod 'yoga', :path => './Test/node_modules/react-native/ReactCommon/yoga'
然后再pod install
就OK了。
以下是博主的官方公众号和小程序,工作之余帮家乡的特产(巫溪牛肉干)做一下推广工作,欢迎关注!
