【问题标题】:Load dynamic assets in react-native在 react-native 中加载动态资产
【发布时间】:2018-04-06 09:18:23
【问题描述】:

如何在 react-native 中实现这一点

require("../images/vehicles/" + this.state.proccessedFirstData.make + ".png")

make是我需要动态访问的对象属性,我一直在寻找,我没有找到任何解决方案

我也试过

const IMAGE = require("../images/vehicles/" + this.state.proccessedFirstData.make + ".png") 不工作

【问题讨论】:

  • 您不能在需要路径中连接变量。其实可以,但不建议这样做,因为它会降低性能。

标签: javascript reactjs react-native jsx


【解决方案1】:

RN 捆绑器是静态的,因此您必须在编译时导入所有资源。

您仍然可以进行半动态加载:

const car1 = require('<path>')
const car2 = require('<path>')
const cars = {car1, car2}

<image source={cars[this.state.car]}>

【讨论】:

    【解决方案2】:

    在 JS 中,require 语句在捆绑时解析(当计算 JS 捆绑时)。因此不支持将变量表达式作为require 的参数。

    如果需要资源,则更加棘手。当您拥有require('./someimage.png') 时,React Native 打包程序将本地化所需的图像,然后将其与应用程序捆绑在一起,以便在您的应用程序运行时将其用作“静态”资源(实际上在开发模式下它不会' t 将图像与您的应用程序捆绑在一起,而是从服务器提供图像,但这在您的情况下并不重要)。

    如果您想使用随机图片作为静态资源,您需要告诉您的应用捆绑该图片。您可以通过以下几种方式做到这一点:

    1) 将其添加为您的应用的静态资产,然后使用&lt;Image src={{uri:'name_of_the_image_in_assets.png'}}/&gt; 引用它(here 是您可以将其添加到本机 iOS 应用的方法)

    2) 静态要求所有图像。某种形式的:

    var randomImages = [
        require('./image1.png'),
        require('./image2.png'),
        require('./image3.png'),
        ...
    ];
    

    然后在你的代码中你可以这样做:

    <Image src={randomImages[Math.floor(Math.random()*randomImages.length)]}/>
    

    3) 使用&lt;Image src={{uri:'http://i.imgur.com/random.jpg'}}/&gt;的网络图片

    ref from this link -- thanks @kzzzf

    【讨论】:

    • 我收到一个错误:require 只需要 1 个字符串文字参数
    • 对不起,它不起作用@NtiyisoRikhotso 我已经更新了我的答案,请检查它
    猜你喜欢
    • 2020-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-10
    • 1970-01-01
    • 2020-06-19
    • 2019-02-26
    • 1970-01-01
    相关资源
    最近更新 更多