1、从0到1创建ReactNative项目,参考https://reactnative.cn/docs/0.51/getting-started.html#content
2、在已有iOS项目(OC)中添加ReactNative模块
1)、在已有的项目的根目录中添加ReactNative文件夹,在该文件夹下创建package.json配置文件,内容如下:
{
"name": "ReactNativeDemo", //创建ReactNative模块时用到的名称
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start", //npm start 执行的命令
"test": "jest"
},
"dependencies": {
"react": "16.3.0-alpha.3",
"react-native": "0.54.2",
"react-navigation": "^1.5.8"
},
"devDependencies": {
"babel-jest": "22.4.3",
"babel-preset-react-native": "4.0.0",
"jest": "22.4.3",
"react-test-renderer": "16.3.0-alpha.3"
},
"jest": {
"preset": "react-native"
}
}
3)、执行npm install 安装ReactNative相关组建,在node_modules文件夹中。
4)、在ReactNativeDemo.xcodeproj平级目录下创建Podfile文件,内容如下
# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'
target 'ReactNativeDemo' do
# Uncomment the next line if you're using Swift or would like to use dynamic frameworks
# use_frameworks!
# Pods for ReactNativeDemo
pod 'React', :path => './ReactNative/node_modules/react-native', :subspecs => [ //这里面写入需要用到的组建名称
'Core',
'ART',
'RCTActionSheet',
'RCTGeolocation',
'RCTImage',
'RCTNetwork',
'RCTPushNotification',
'RCTSettings',
'RCTText',
'RCTVibration',
'RCTWebSocket',
'RCTLinkingIOS',
# Add any other subspecs you want to use in your project
]
target 'ReactNativeDemoTests' do
inherit! :search_paths
# Pods for testing
end
target 'ReactNativeDemoUITests' do
inherit! :search_paths
# Pods for testing
end
end
5)、执行pod install
6)、在ReactNative文件夹下创建index.js文件,内容如下:
import { AppRegistry } from 'react-native';
import App from './App';
AppRegistry.registerComponent("ReactNativeDemo",() => App);
7)、在ReactNative文件夹下创建App.js文件,内容如下:
import React ,{Component} from 'react';
import {
Platform,
StyleSheet,
View,
Text
} from 'react-native'
export default class App extends Component {
render(){
return(
<View style={{top:30,left:30}}>
<Text style={{color:'red',fontSize:30}}>Component</Text>
<Text style={{color:'blue',fontSize:30}}>Component</Text>
</View>
);
}
}
8)、原生端加载方式代码:
NSURL *jsCodeLocation = [NSURL
URLWithString:@"http://localhost:8081/index.bundle?platform=ios"];
RCTRootView *rootView =
[[RCTRootView alloc] initWithBundleURL : jsCodeLocation
moduleName : @"ReactNativeDemo"
initialProperties :
@{
@"scores" : @[
@{
@"name" : @"Alex",
@"value": @"42"
},
@{
@"name" : @"Joel",
@"value": @"10"
}
]
} launchOptions : nil];
结构目录如下: