ios native工程集成react-native的demo

时间:2023-03-09 08:17:17
ios native工程集成react-native的demo

react-native看到了给现有工程添加react-native环境的时候碰到一个问题:

如何往工程中添加 package.json文件,以及node_modules是怎么来的?

我开始的时候以为是自己创建的文件夹,package.json文件也是通过vim来写的。

但是就在写package.json时 写了一下我就感觉特别不方便。于是我想到了npm:node package manager. 尝试了一下,果然通过npm可以帮助我们完成这项任务。

具体操作:

1、进入你工程的根目录

2、npm init (这个工作跟cocoapods的podfile文件初始化有点像)-> 根据提示输入工程的package.json的内容。

3、npm install

经过上述的步骤之后我们的工程根目录底下就有了react-native的环境了。

然后此时我要导入的redux框架,这时候我只要往dependcies中增加:

"name": "RNIntergrationDemo",

"version": "0.0.1",
"private": true,
"scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start",
"test": "jest"
},
"dependencies": {
"react": "15.4.1",
"react-native": "0.39.2",
"redux":"3.6.0"
},
"devDependencies": {
"babel-jest": "18.0.0",
"babel-preset-react-native": "1.9.1",
"jest": "18.1.0",
"react-test-renderer": "15.4.1"
},
"jest": {
"preset": "react-native"
}

接下来是配置podfile:

进入工程根目录下的ios目录(就是有xproject文件的目录),然后通过CocoaPods进行初始化:pod init操作

生成Podfile

在Podfile中你的工程的target 名字下 添加对React-Native支持的依赖框架

pod 'React':path=>'../node_modules/react-native',subspecs=>[

'Core',

'RCTText',

'RCTNetwork',

'RCTWebSocket']

这样你的依赖就添加好了。

接下来操作是:

1、把你的 (index.ios.js )js代码写好。

2、在具体页面中加载这个你刚才写好的的这个js

加载方法:

a、初始化js加载路径:

NSURL *jsCodeLocation = [NSURL URLWithString:@"http://localhost:8081/index.ios.bundle?platform=ios"];

b、在ViewController的loadView方法中初始化一个RCTRootView并设置成当前ViewController的view。

tform=ios"];

RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation moduleName:@"你js中的register的component名字" initialProperties :

@{

@"scores" : @[

@{

@"name" : @"Alex",

@"value": @"42"

},

@{

@"name" : @"Joel",

@"value": @"10"

} ]

} launchOptions:nil];

由于你的js加载路径是http协议的本地路径,所以你要设置一下info.plist才能访问到(设置ATS),只要加上Allow Arbitrary Loads属性设置为YES就可以了。最后上传一下demo.

https://github.com/zLihuan/RNIOSIntergrationDemo.git demo的用法在github的README上可以看到。

其实就是跟着facebook的集成步骤一步一步来的。【大写的