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

来源:互联网 发布:怎么让mac运行exe 编辑:程序博客网 时间:2024/06/10 04:41

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演示:

这里写图片描述

0 0