目录

  • 一. 原生iOS项目集成React Native
  • 二. 原生跳转RN页面
  • 三. 显示豆瓣热门电影列表
  • 四. 改为导航
  • 五.完整源代码

一. 原生iOS项目集成React Native

  1. 创建一个新的文件夹,如RNProject,然后新建一个/ios的子文件夹,将已有的iOS项目全部文件复制进去。

  2. 在RNProject根目录创建package.json文件,内容如下:

{"name": "RNProject","version": "1.0.0","private": true,"scripts": {"start": "yarn react-native start"}
}
  1. 打开终端,cd到项目根目录,执行以下命令集成React Native模块:
$ yarn add react-native
  1. 等待上一步完成后,注意红框内的提示,表示需要依赖指定版本的react。我们以下命令集成react,注意版本号需要严格按照提示的要求:
$ yarn add react@16.8.3

此时所有集成的依赖都在node_modules/目录下,做git版本控制时,不应该上传此文件夹的所有文件,而是让其他协作者也执 行以上命令来添加依赖。因此应该将node_modules/目录记录到.gitignore文件中。

  1. 通过cocoaPods将React Native集成到iOS项目中。默认你已经熟悉并安装了cocoaPods。在终端中,cd到/ios目录下,初始化cocoaPods:
$ pod init

打开Podfile文件,编辑为如下内容:

# The target name is most likely the name of your project.
target 'RNProject' do# Your 'node_modules' directory is probably in the root of your project,# but if not, adjust the `:path` accordinglypod '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','RCTImage','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.0pod 'yoga', :path => '../node_modules/react-native/ReactCommon/yoga'# Third party deps podspec linkpod '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 ‘RNProject’ do中为iOS项目的名称,而不是根目录名称,只是这里我的根目录和iOS项目名称均为RNProject。
保存Podfile后,执行以下命令开始安装:

$ pod install

至此,就已经成功在已有iOS项目中集成了RN,项目文件结构如下:

二. 原生跳转RN页面

  1. 苹果会阻止访问不安全的HTTP链接。我们需要在iOS项目的Info.plist的中添加:
<key>NSAppTransportSecurity</key>
<dict><key>NSExceptionDomains</key><dict><key>localhost</key><dict><key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key><true/></dict></dict>
</dict>

  1. 在根目录下创建index.js文件,作为React Native在iOS上的入口文件。并输入以下内容:
import React from 'react';
import {AppRegistry, StyleSheet, Text, View} from 'react-native';class Hello extends React.Component {render() {var {name} = this.propsreturn (<View style={{flex: 1,justifyContent: 'center',alignItems: 'center'}}><Text>Hello {name}!</Text></View>);}
}AppRegistry.registerComponent('Hello', () => Hello);
  1. 在Xcode中,创建一个ViewController,并输入以下内容:
#import "ViewController.h"
#import <React/RCTRootView.h>@implementation ViewController- (void)viewDidLoad {[super viewDidLoad];UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 200, 50)];button.center = self.view.center;[button setTitle:@"跳转RN" forState:0];[button setTitleColor:[UIColor greenColor] forState:0];[button addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpInside];[self.view addSubview:button];
}- (void)clickButton:(UIButton*)button{NSURL *jsCodeLocation = [NSURL URLWithString:@"http://localhost:8081/index.bundle?platform=ios"];RCTRootView *rootView =[[RCTRootView alloc] initWithBundleURL: jsCodeLocationmoduleName: @"Hello"initialProperties: @{@"name":@"React Native"}launchOptions: nil];UIViewController *vc = [[UIViewController alloc] init];vc.view = rootView;[self presentViewController:vc animated:YES completion:nil];
}@end
  1. 在根目录使用以下命令启动RN Packager
npm start
  1. 在Xcode中运行项目,运行后点击“跳转RN”后,既会跳转到RN实现的显示Hello React Native!的页面:

三. 显示豆瓣热门电影列表

每个页面应该对应独立的一个js文件,并且为了防止项目大了以后保持文件结构的清晰,我们为热门电影列表创建如下目录及文件:./src/page/HotMovie.js,在HotMovie.js中输入以下内容:

import React, {Component} from 'react';
import {StyleSheet, Image, Text, View, FlatList} from 'react-native';var REQUEST_URL = "https://movie.douban.com/j/search_subjects?type=movie&tag=%E7%83%AD%E9%97%A8&sort=recommend&page_limit=20&page_start=0"export default class HotMovie extends Component<Props> {constructor(props){super(props);this.state = {movies:null,}this.fetchData = this.fetchData.bind(this)}componentDidMount(){this.fetchData()}fetchData(){fetch(REQUEST_URL).then((response) => response.json()).then((responseJson) => {this.setState({movies:responseJson.subjects});})}render() {if (!this.state.movies) {return this.renderLoadingView();}return (<FlatListdata={this.state.movies}renderItem={this.renderMovie}style={styles.list}keyExtractor={item => item.id}/>);}renderLoadingView(){return (<View style={styles.container}><Text>正在加载...</Text></View>)}renderMovie({item}){return(<View style={styles.item}><Image source={{url:item.cover}} style={styles.thumbnail}/><View style={styles.itemRight}><Text>{item.title}</Text><Text>{item.rate}</Text></View></View>)}}const styles = StyleSheet.create({container: {flex:1,flexDirection:'row',alignItems:'center',justifyContent: 'center',alignItems: 'center',},item:{marginTop:1,flexDirection:'row',alignItems:'center',justifyContent: 'center',height:100,backgroundColor:'lightgray'},thumbnail:{width:53,height:81,backgroundColor:'lightgray'},itemRight:{flex:1,height:100,justifyContent: 'center',alignItems:'center'},list: {paddingTop: 50,backgroundColor: "#F5FCFF"}
});

2、将index.js修改为如下:

import React from 'react';
import {AppRegistry, StyleSheet, Text, View} from 'react-native';
import HotMovie from './src/page/HotMovie';AppRegistry.registerComponent('HotMovie', () => HotMovie);

3、原生将按钮点击事件改为:

- (void)clickButton:(UIButton*)button{NSURL *jsCodeLocation = [NSURL URLWithString:@"http://localhost:8081/index.bundle?platform=ios"];RCTRootView *rootView =[[RCTRootView alloc] initWithBundleURL: jsCodeLocationmoduleName: @"HotMovie"initialProperties: nillaunchOptions: nil];UIViewController *vc = [[UIViewController alloc] init];vc.view = rootView;[self presentViewController:vc animated:YES completion:nil];
}

3、运行后的效果如图:

四. 改为导航

篇幅有点长啦,另开一篇继续 https://blog.csdn.net/dolacmeng/article/details/90414040

五.完整源代码

戳 https://github.com/dolacmeng/RNProject/tree/master

给iOS开发者的React Native入门使用教程相关推荐

  1. React Native 入门实战视频教程(36 个视频)

    React Native 入门实战视频教程(36 个视频) #1 React Native 课程介绍「02:14」 #2 搭建 React Native 开发与运行环境跑起来「05:07」 #3 演示 ...

  2. React Native 入门实战视频教程(37 个视频)

    我这里有视频教程,全部是我自己辛苦录的,有兴趣的可以看下. React Native 入门实战视频教程(37 个视频) 从零开始入门学习 React Native 开发,手把手教你写 App 项目 # ...

  3. 如何在iOS上运行React Native应用

    by Soujanya PS 通过Soujanya PS 如何在iOS上运行React Native应用 (How to run a React Native app on iOS) I recent ...

  4. React Native 入门实战视频教程(4 个视频)

    React Native 入门实战视频教程(4 个视频) #1 React Native 课程介绍「02:14」 #2 搭建 React Native 开发与运行环境跑起来「05:07」 #3 演示在 ...

  5. 菜鸟窝Android百度云视频,菜鸟窝React Native 视频系列教程

    菜鸟窝React Native 视频系列教程 交流QQ群:276960232 Hi,我是RichardCao,现任新美大酒店旅游事业群的Android Developer.15年加入饿了么即时配送BU ...

  6. 给所有开发者的React Native详细入门指南

    本文为 Marno 原创,转载必须保留出处! 公众号[ aMarno ],关注后回复 RN 加入交流群 React Native 优秀开源项目大全:http://www.marno.cn 建议先下载好 ...

  7. React Native入门(十四)之动画(1)Animated详解

    前言 在APP的开发中,流畅合理的动画能大大提高用户体验,Android和iOS原生都有对应的动画系统,同样的在RN中也有用于创建动画的API,就是Animated.Animated库使得开发者可以非 ...

  8. React Native入门 基础使用总结

    1.router: react-native-router-flux 基于react-navigation/native 二次封装 2.字体图标:react-native-vector-icons(推 ...

  9. React Native 入门踩坑

    开发环境搭建及环境变量配置 开发rn第一步需要配置安卓环境 android studio下载地址: https://developer.android.google.cn/studio/archive ...

最新文章

  1. StarUML中时序图添加小人
  2. 为什么Java的+ =,-=,* =,/ =复合赋值运算符不需要强制转换?
  3. 【微信小程序企业级开发教程】后台用Java操作MySQL表
  4. 建立广域网时使用的拓扑结构是什么?
  5. Redis的Expire与Setex
  6. 马克·扎克伯格帝国的衰落
  7. SQL删除数据表中指定列重复的数据
  8. App内存优化-实践
  9. 微软数据视界:图解数据分析价值
  10. 如何使用ant_从 0 开始,成为 Ant-Design Contributor
  11. 一建已经过去,正是中级通信工程师黄金备考期!
  12. 小白入门,Shell脚本,编写脚本显示信息,编写脚本自动创建文件,编写脚本对数据进行双硬盘备份
  13. 如果大一光靠自己学,华为HICE能过的几率大吗?
  14. rtklib 后处理_RTKLib的Manual解读
  15. 绩效考核管理方案文档
  16. NVIDIA显卡驱动程序更新失败解决记录
  17. Java初学笔记30-【MiniQQ聊天部分代码】
  18. 微软服务器系统突然要求密钥,买了Win10新电脑?小心微软偷走你的设备加密密钥...
  19. 一个矩阵与单位矩阵相乘等于本身吗?并且符合交换律吗?
  20. 在PCLVisualizer中添加坐标轴和图片和颜色表

热门文章

  1. C++ template
  2. 【OpenCV】图像代数运算:平均值去噪,减去背景
  3. PDF编辑工具——PDF Desktop Converter 4 Professional
  4. JavaServer Faces技术
  5. 警惕企业中的五种虚假执行力
  6. 多传感器融合之滤波(二)EKF
  7. Spring4实战学习笔记
  8. 负载均衡环境中和如何设置Expires和Etag
  9. Fedora 15 安装与配置一览
  10. CDMA模块上网设置的过程