美文网首页
如何在源生项目中使用 React Native

如何在源生项目中使用 React Native

作者: _白丁_ | 来源:发表于2016-12-09 13:04 被阅读290次

    React Native 如何真机 release 模式运行
    React Native 如何用 Pushy 进行热更新

    如果你觉得对你有所帮助, 记得【关注】,感谢支持,后期还会有更新。

    一、准备工作

    首先你需要一个 React Native 的环境,如果还没有请看下面文章
    搭建 React Native 的开发环境

    二、创建一个 React Native 项目

    1)打开你的终端创建一个新的 React Native 项目
    操作指令如下

    $ cd Desktop
    $ react-native init HelloWorld
    

    2)创建完毕时,你的桌面会有一个 HelloWorld 的项目,打开里面的 packager.json 将其 HelloWorld 换成你项目的名字

    Paste_Image.png
    3)在你 源生 的项目的 根目录 中创建一个文件夹 ReactNative 的文件夹,
    并且将刚才创建的 HelloWorld 项目中的
    package.jsonindex.ios.js 还有 index.android.js 文件复制进去。
    如下图所示
    Paste_Image.png
    4)在终端输入如下指令
    $ cd <将你刚才创建的 ReactNative 文件夹拖这里后回车>
    

    然后使用 npm 安装 react-native 组件

    $ npm install
    

    完成之后会生成一个 node_module 文件夹


    Paste_Image.png

    三、在源生中接入

    • 在你需要使用 React Native 的模块中
      创建一个 ReactViewController 来管理 React 组件

    • 具体代码如下

    //
    //  CSReactViewController.m
    //  ChiefSteward
    //
    //  Created by CoderXSLee on 16/12/2.
    //  Copyright © 2016年 李雪松. All rights reserved.
    //
    #import "CSReactViewController.h"
    #import <React/RCTBundleURLProvider.h>
    #import <React/RCTRootView.h>
    @interface CSReactViewController ()
    {
        RCTRootView *_rootView;
    }
    @end
    @implementation CSReactViewController
    - (instancetype)init {
        if (self = [super init]) {
            [self initReactView];
        }
        return self;
    }
    -(void)loadView {
        [super loadView];
        self.view = _rootView;
    }
    - (void)viewDidLoad {
        [super viewDidLoad];
    }
    - (void)initReactView {
        NSURL *jsCodeLocation;
    #ifdef DEBUG
        jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index.ios" fallbackResource:nil];
    #else
        // 这里暂时不用热更新先注释掉
        // jsCodeLocation = [RCTHotUpdate bundleURL];
    #endif
        _rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
                                                moduleName:@"ChiefSteward"
                                         initialProperties:nil
                                             launchOptions:nil];
    }
    @end
    

    其中 moduleName: 是你 源生 项目的名称,不要忘记换了啊!

    四、运行项目

    • debug 模式 ---> 模拟器运行

    打开终端进入你项目的根目录 也就是 package.json 的那一级目录
    执行如下代码开启 react 服务

    $ react-native start
    

    好了,到这里你已经完成了!
    赶快在 Xcode 中使用 Command + R 跑起来看一下吧!

    • release 模式 ---> 真机上运行

    React Native 如何真机 release 模式运行

    好了,到这里你已经完成了! 使用 Command + R

    如果你觉得我的文章对你有帮助,向我发个红包吧!
    我将衷心德感谢你对我的支持!你的支持就是我的动力!

    微信扫码向我发红包

    微信.jpeg

    支付宝扫码向我发红包

    支付宝.jpeg

    相关文章

      网友评论

          本文标题:如何在源生项目中使用 React Native

          本文链接:https://www.haomeiwen.com/subject/ycvemttx.html