简体   繁体   中英

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

I also tried

const IMAGE = require("../images/vehicles/" + this.state.proccessedFirstData.make + ".png") and its not working

In JS require statements are resolved at bundle time (when the JS bundle is calculated). Therefore it's not supported to put variable expression as an argument for 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).

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)

2) Require all the images upfront statically. Sth in a form of:

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'}}/>

ref from this link -- thanks @kzzzf

The RN bundler is static so you have to import all the resources at compile time.

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]}>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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