简体   繁体   English

将动态资产加载到本地

[英]Load dynamic assets in react-native

How can I achieve this in react-native 我如何在本机中实现这一目标

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

make is the object property that I need to access dynamically, I have been searching around and I am not finding any solution make是我需要动态访问的对象属性,我一直在搜索并且没有找到任何解决方案

I also tried 我也试过

const IMAGE = require("../images/vehicles/" + this.state.proccessedFirstData.make + ".png") and its not working const IMAGE = require("../images/vehicles/" + this.state.proccessedFirstData.make + ".png")并且无法正常工作

In JS require statements are resolved at bundle time (when the JS bundle is calculated). 在JS中,require语句在捆绑包时间(计算JS捆绑包时)解析。 Therefore it's not supported to put variable expression as an argument for require . 因此,不支持将变量表达式作为require的参数。

In case of requiring resources it's even more trickier. 如果需要资源,则更加棘手。 When you have require('./someimage.png') , React Native packager will locale required image and it will be then bundled together with the app so that it can be used as a "static" resource when your app is running (in fact in dev mode it won't bundle the image with your app but instead the image will be served from the server, but this doesn't matter in your case). 当您具有require('./someimage.png') ,React Native打包器将对所需图像进行语言环境设置,然后将其与应用程序捆绑在一起,以便在您的应用程序运行时可用作“静态”资源(在实际上,在开发人员模式下,它不会将图像与您的应用捆绑在一起,而是会从服务器提供图像,但这对您而言并不重要。

If you want to use random image as a static resource you'd need to tell your app to bundle that image. 如果您要将随机图片用作静态资源,则需要告诉您的应用捆绑该图片。 You can do it in a few ways: 您可以通过以下几种方式进行操作:

1) Add it as a static asset of your app, then reference to it with <Image src={{uri:'name_of_the_image_in_assets.png'}}/> ( here is how you can add it to the native iOS app) 1)将其添加为应用程序的静态资产,然后使用<Image src={{uri:'name_of_the_image_in_assets.png'}}/>对其进行引用( 是将其添加到本地iOS应用程序的方法)

2) Require all the images upfront statically. 2)静态要求所有图像。 Sth in a form of: Sth的形式:

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

Then in your code you can do: 然后,您可以在代码中执行以下操作:

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

3) Use network image with <Image src={{uri:'http://i.imgur.com/random.jpg'}}/> 3)将网络映像与<Image src={{uri:'http://i.imgur.com/random.jpg'}}/>

ref from this link -- thanks @kzzzf 来自此链接的引用-谢谢@kzzzf

The RN bundler is static so you have to import all the resources at compile time. RN捆绑程序是静态的,因此您必须在编译时导入所有资源。

You can still have a semi dynamic load: 您仍然可以承受半动态负载:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM