IOS原生集成ReactNative
折腾了一天,看到网上很多帖子说原生集成RN使用cocopods 会报各种奇葩的错误,给我吓得赶紧使用拖拉文件的方式。哪知道一直没成功。尝试了下cocoapods集成RN,成功了,下面来分享下我的成功,嘻嘻~
1.首先新建个xcode工程
2.使用终端命令react-native init xxx ;xxx是RN的项目名称.
3.新建一个文件存放RN集成到IOS原生项目需要的文件。如图RNCompent是新建的文件夹,吧第二部RN项目里的index.js /node_modules/package.json 这三个文件拷贝到RNCompent文件夹下。
4.index.js 代码如下
import React, { Component } from 'react';
import {
AppRegistry, StyleSheet, Text, View, Image
} from 'react-native';
export default class RNT extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
nethanhan
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
}
});
//这里的名字后面需要用到 RNT
AppRegistry.registerComponent('RNT', () => RNT);
以上代码中 AppRegistry.registerComponent('RNT', () => RNT); 这句话很重要,是IOS集成RN的一个入口,RNT名字可以随便起,作为后面的一个标示。
5.吧RNCompent文件夹拖到IOS原生项目的根目录下,如下图文件路径。以及RNCompent文件内容
7.终端cd 到 RNTEST文件夹下,pod init ,成功之后vim Podfile。Podfile 内容如下:
# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'
target 'RNTEST' do
# Uncomment the next line if you're using Swift or would like to use dynamic frameworks
# use_frameworks!
# Pods for RNTEST
pod 'React', :path => '../RNCompent/node_modules/react-native', :subspecs => [
'Core',
'CxxBridge', # 如果RN版本 >= 0.47则加入此行
'DevSupport', # 如果RN版本 >= 0.43,则需要加入此行才能开启开发者菜单
'RCTText',
'RCTNetwork',
'RCTWebSocket', # 调试功能需要此模块
'RCTAnimation', # FlatList和原生动画功能需要此模块
# 在这里继续添加你所需要的其他RN模块
]
# 如果你的RN版本 >= 0.42.0,则加入下面这行
pod 'yoga', :path => '../RNCompent/node_modules/react-native/ReactCommon/yoga'
pod 'Folly', :podspec => '../RNCompent/node_modules/react-native/third-party-podspecs/Folly.podspec'
end
yoga /folly 的路径写错了,会报“Unable to find a specification for `yoga (= 0.57.0.React)`” 错误,以及以下编译错误
6.Podfile完成之后,保存退出,在终端执行pod Install 命令。成功之后进入项目。
7.
8,至此IOS原生集成React Native算是完成了,有问题留言哦~