之前解决了字符串拼接:
后,然后用代码:
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’)} /> |
会报错。