美文网首页
React Native 多组件方案

React Native 多组件方案

作者: tsiic | 来源:发表于2017-09-15 14:45 被阅读0次

出于各方面考量一般 React Native 不会制作大型组件,这意味着 React Native 不会制作完整 APP 或者占据软件核心,在这种情况下 React Native 在程序中处于组件状态,因而在一个 APP 中可能存在多个组件。

多组件情况下市面上有几种处理方案:
第一种就是注册多个组件


image.png

这样会出现内存消耗问题。

第二种是只注册一个组件
形式如下

import React, {Component} from 'react';
import {AppRegistry,} from 'react-native';
import RNEntrance1 from './js/RNEntrance1'
import RNEntrance2 from './js/RNEntrance2'
import RNEntrance3 from './js/RNEntrance3'

class Root extends Component {
    render() {
        switch (this.props.entrance) {
            case 1:
                return <RNEntrance1 />
            case 2:
                return <RNEntrance2 />
            case 3:
                return <RNEntrance3 />
        }

    }
}
AppRegistry.registerComponent('RNActivity', () => Root);

根据网上的测试数据,这种方式并没有效率上的提升,并且这两种方法都面临一个问题,就是 这两种方案都是建立在 JS 端模块都建立在同一个工程内。

结合以上观点,考虑到以模块为单位的 React Native 很有可能是多个工程并行开发,计划采用多个 JSCoreLocation 的方式,也就是通过在原生端预定义地址。
使用以下形式的代码:

let jsCodeLocation = Bundle.main.url(forResource: "loginWithPasswordScreen.ios", withExtension: "jsbundle")
// or
// let jsCodeLocation = Bundle.main.url(forResource: "index.ios", withExtension: "jsbundle")

let rootView = RCTRootView(
     bundleURL: jsCodeLocation,
     moduleName: "Login",
     initialProperties: mockData as! [AnyHashable : Any] ,
     launchOptions: nil
     )

这种形式需要预先打包内置 jsbundle 文件,否则地址为空无法加载。

在实际项目中我们使用 React Native 往往不会丢弃动态更新这个我们非常重视的优势,因此很多时候 jscorelocation 都不在 main bundle 里,以上代码仅作为示例,实际上大多数人都会在开始的时候把 bundle 里的文件拷贝到 documents 目录下,而笔者更喜欢使用辅助类去动态判断读取路径,let path2 = FilePathManager.getFilePath(forResource: "HomeData", ofType: "json")这样可以省去不必要的拷贝。
参考资料:

http://react-china.org/t/ios-rn/7670
https://segmentfault.com/a/1190000009977479

相关文章

网友评论

      本文标题:React Native 多组件方案

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