React Native Image component requiring an unknown module

The docs make it pretty clear that you cannot perform dynamic execution:

// GOOD
<Image source={require('./my-icon.png')} />

// BAD
var icon = this.props.active ? 'my-icon-active' : 'my-icon-inactive';
<Image source={require('./' + icon + '.png')} />

// GOOD
var icon = this.props.active ? require('./my-icon-active.png') : require('./my-icon-inactive.png');
<Image source={icon} />

I have a use case that is not cut and dry that way, but I have a ListView and in the renderRow method I would like to make an image depending on some data in the specified row. For example, I want to do .. / img / 12.png by doing this

<Image style={styles.thumb} source={require("../img/12.png")} />

works fine however

let imagePath = "../img/" + row.number + ".png";  // row.number being 12
<Image style={styles.thumb} source={require(imagePath)} />

gives the following error:

Requiring unknown module "../img/12.png"

Is there any workaround here, it looks like it still ends up requiring the exact same line, it just doesn't work.

+4
source share
2 answers

you need to do:

let imagePath = require("../img/" + row.number + ".png")
<Image style={styles.thumb} source={imagePath} />
+1
source

Well, I realized this and decided that I would send an answer if someone in the future struggles.

, , , , .

: , ( "../img/x.png" ), x . ListView , , row.number

+1

Source: https://habr.com/ru/post/1650230/


All Articles