Why can't string variable be used in <Image source={}/>? (React Native)

情到浓时终转凉″ 提交于 2019-12-12 03:04:26

问题


I am trying to do the following:

var itemImage = '../img/image1.jpg'

return(
        <Image
          source={require(itemImage)}
        />

but it keeps saying the error:

Requiring unknown module '../img/image1.jpg'. 

But when I directly put in: '../img/image1.jpg' inside require() then it works.

What may be the issue? Any guidance or insight would be appreciated.

EDIT ***

I have the following in my constructor as my dataSource:

this.state = {dataSource: ds.cloneWithRows([{name: '../img/item1.jpg'}, {name: '../img/item2.jpg'}])}

then in my renderRow(), I am trying to achieve something like the following so it updates based on the dataSource:

renderRow(rowData){
    var itemImage = require(rowData.name)

    return(
            <Image
              source={itemImage}
            />

But I am still getting the same error:

Requiring unknown module '../img/image1.jpg'. 

回答1:


Using require with any resource file is a special case. It is not common javascript require. Packager must know what image will be required while building application (before any code executed) to replace it with resource ID. So parameter can't be variable and must be constant.

But you can simply do:

{
   dataSource: ds.cloneWithRows([
       {image: require('../img/item1.jpg')},
       {image: require('../img/item2.jpg')}
   ])
}



回答2:


Try this with single curly brace in image source. and storing image path in image variable with require() method.

render(){
    var image=require('../img/image1.jpg');
    return(
       <View >
           <Image source={image}/>
       </View>
      );
 }


来源:https://stackoverflow.com/questions/38366191/why-cant-string-variable-be-used-in-image-source-react-native

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!