简体   繁体   中英

React Native, how to add a variable inside image link with require function

I stored images locally in project folder, and I want to add a variable (nature.png) inside image source (with require), so I did like this

let i = 'natrue';
let imagePath = require('../asset/gallery/image/');
    return (
        <View >
            <Image source={{imagePath} + i + '.png'}/>
        </View>

But I got an error:

text string must be rendered within a text component

And I dont want to do like this (Works fine) because I have more than 100 images:

<Image source={require('../asset/gallery/image/nature.png')} />

Unfournately requirejs module doesn't work that way

You'll have to create strings completely or create a object which will map a key to image. Also that is a best practice to follow.

you can create a file called image.js and export all your images from there,

for example

// image.js

const BASE_URL = "../asset/gallery/image/";

export default {
  nature:require(`${BASE_URL}nature.png`),
}

and in your components,

import Images from "src/images";

...
<>
   <Image src={Images.nature}/>
</>
...

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