您的位置:首页 > Web前端 > React

React Native学习笔记之--向原生应用中集成RN页面

2017-01-18 14:57 836 查看

React Native学习笔记之–向原生应用中集成RN页面

根据在官方文档的学习要向已有的原生项目中添加RN组件最重要的就是以下几步:


1.Understand what React Native components you want to integrate.

2.Create a Podfile with subspecs for all the React Native components you will need for your integration.

3.Create your actual React Native components in JavaScript.

4.Add a new event handler that creates a RCTRootView that points to your React Native component and its AppRegistry name that you defined in index.ios.js.

5.Start the React Native server and run your native application.

6.Optionally add more React Native components.

下面就一步一步的向原生项目中集成RN组件:

1、官方说集成RN需要package.json和index.ios.js两个文件,Xcode创建的工程是没有的,这里我是从一个空的RN项目中拷贝过来的,然后将package.json中的name修改为自己需要的。项目目录结构也是照着原始创建的。







2、进入package.json所在的目录,利用npm导入React Native需要的包资源,执行npm install



出现如上图所示表示资源包导入成功,并且可以查看该目录下有一个node_modules目录。

3、创建Podfile文件,利用CocoaPods导入需要使用的RN组件





到这里表示RN的环境已经集成到原生的项目工程中了。

4、在原生界面跳转到RN界面中

这里我通过触发StoryBoard中按钮跳转到RN界面,部分代码如下(官方文档也给出了比较详细的介绍):

@IBAction func jumpRNPage(_ sender: UIButton) {
let jsCodeLocation = NSURL.init(string: "http://localhost:8081/index.ios.bundle?platform=ios")
let rootView = RCTRootView.init(bundleURL: jsCodeLocation as URL!, moduleName: "RNDemoComponent", initialProperties: nil, launchOptions: nil)
let rnPageVc = UIViewController()
rnPageVc.view = rootView
navigationController?.pushViewController(rnPageVc, animated: true)
}


在项目中还需要对http做配置,否则会出现连接不到服务的错误,要想运行项目还需要在控制台进入项目的根目录执行react-native start来启动服务。





demo演示:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: