iOS 在原生项目中使用 React Native

本文的前提是电脑已经安装过React-Native相关环境和cocoapods

STEP 1 安装node_modules包

创建package.json文件
在项目的根目录下,这是为工程添加依赖库。里面有工程的版本信息和所需要的依赖库,第三方库等
偷懒的做法是直接输入命令

react-native init HelloWord

然后打开HelloWord根目录的 package.json文件 将HelloWord改成你的APP名字

{
    "name": "HelloWord",
    "version": "0.0.1",
    "private": true,
    "scripts": {
        "start": "node node_modules/react-native/local-cli/cli.js start",
        "test": "jest"
    },
    "dependencies": {
        "react": "15.4.2",
        "react-native": "0.41.2"
    },
    "devDependencies": {
        "babel-jest": "19.0.0",
        "babel-preset-react-native": "1.9.1",
        "jest": "19.0.2",
        "react-test-renderer": "15.4.2"
    },
    "jest": {
        "preset": "react-native"
    }
}

然后在项目的根目录下

npm install

STEP 2 添加pod所需要的库到工程

创建podfile文件,利用Cocoapods安装podfile中所涉及到的库

target 'YourProjectName' do

#你的其他第三方依赖#

pod ‘React’, :path => ‘./node_modules/react-native’, :subspecs => [
‘Core’,
'ART',  
  'RCTActionSheet',  
  'RCTAdSupport',  
  'RCTGeolocation',  
  'RCTImage',  
  'RCTNetwork',  
  'RCTPushNotification',  
  'RCTSettings',  
  'RCTText',  
  'RCTVibration',  
  'RCTWebSocket',  
  'RCTLinkingIOS',  
] 
end

然后进行 pod install安装库

pod install

STEP 3 创建index.ios.js文件

可以把刚才创建的HelloWord中的index.ios.js文件拿过来
但是记得修改index.ios.js里面的工程名字

项目截图.png

STEP 4添加到原生项目

在任意一个界面导入头文件

#import "RCTBundleURLProvider.h"
#import "RCTRootView.h"
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"RN接入测试";
//手动设置IP
//RCTBundleURLProvider在接口中暴露了 jsLocation 属性,可以通过 setJsLocation 手动设置IP。
//另需要在Info设置 NSAppTransportSecurity 的 NSAllowsArbitraryLoads 为 true 即可。
//RCTBundleURLProvider 类做了一些消息和属性的封装,可以通过判断是否DEBUG环境然后做不同的设置。 
    [[RCTBundleURLProvider sharedSettings] setDefaults];
#if DEBUG
    [[RCTBundleURLProvider sharedSettings] setJsLocation:@"192.168.1.211"];
#endif
    NSURL *jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index.ios" fallbackResource:nil];
    RCTRootView *rootView =
    [[RCTRootView alloc] initWithBundleURL : jsCodeLocation
                             moduleName : @"buios"
                         initialProperties :nil
                          launchOptions : nil];
    rootView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    [self.view addSubview:rootView];
}

到这里基本就结束了,但是现在运行会提示服务器没有打开,这时候在根目录下npm start 开启服务器,在运行项目或者react-native run-ios。就大功告成了。

简单记录一下自己实践过有效的方式,自学扒资料好费劲,如果有需要 XMG11期RN入门视频的可以联系我,感觉挺有用的

最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容