最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】ReactNative中加载图片失败:Unknown named module

React Native crifan 4165浏览 0评论

之前解决了字符串拼接:

【已解决】ReactNative中字符串拼接

后,然后用代码:

        const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
        this.state = {
            dataSource: ds.cloneWithRows([
                {
                    intentionLevel : "H",
                    customerName : "王小丫",
                    intentionCar : "奥迪A3进口",
                    updateTime : "2016/12/28"
                },
                            <Image style={styles.intentionLevel} source={require(‘./img/customerLevel_’ + rowData.intentionLevel + ‘.png’)} />

结果出错:

Unknown named module ‘./img/customerLevel_H.png’

但是很怪的是:

之前用类似代码:

<Image style={styles.intentionLevel} source={require(‘./img/customerLevel_A.png’)} />

是可以正常运行的:

且此处确保对应目录下是有对应图片的:

然后后来注意到了:

Images – React Native | A framework for building native apps using React

中提到了:

“Note that in order for this to work, the image name in require has to be known statically.

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

-》

意思是:

require中的图片文件名,必须是静态,在编译之前就确定下来的

-》ReactNative内部应该会自动事先去查找该图片。

【总结】

ReactNative中,如果使用require去加载图片,则图片的文件名必须是静态static的

-》不能是通过变量字符串动态生成的

-》所以这种静态的:

<Image style={styles.intentionLevel} source={require(‘./img/customerLevel_A.png’)} />

可以工作的

-》而动态生成的:

<Image style={styles.intentionLevel} source={require(‘./img/customerLevel_’ + rowData.intentionLevel + ‘.png’)} />

会报错。

转载请注明:在路上 » 【已解决】ReactNative中加载图片失败:Unknown named module

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
84 queries in 0.186 seconds, using 22.10MB memory