给出下面的代码,反应本机抱怨
Requiring unknown module "../../images/Foo.png".If you are sure the module is there, try restarting the packager or running "npm install".
但是如果我将图像源路径硬编码在中,相同的代码可以正常工作require
call.
代码不起作用:有一个方法调用来确定图标名称。注意require('../../images/'+imageIconNameFor(prediction.type)
line.
const PredictionItem = ({prediction}) => (
<TouchableHighlight onPress={() => itemPressed()}>
<View style={styles.predictionItem}>
<Image style={styles.predictionIcon} source={require('../../images/'+imageIconNameFor(prediction.type))}></Image>
</View>
</TouchableHighlight>
);
function imageIconNameFor(predictionType) {
return "Foo.png";
}
代码工作:如果我将图标名称硬编码在require
打电话,效果很好。注意require('../../images/Foo.png')
line.
const PredictionItem = ({prediction}) => (
<TouchableHighlight onPress={() => itemPressed()}>
<View style={styles.predictionItem}>
<Image style={styles.predictionIcon} source={require('../../images/Foo.png')}></Image>
</View>
</TouchableHighlight>
);
function imageIconNameFor(predictionType) {
return "Foo.png";
}
当我连接字符串来构建图像源时,为什么会有不同的行为?
Why require('../../images/'+imageIconNameFor(prediction.type)
无法渲染图像,但是require('../../images/Foo.png')
工作正常?
请注意,方法调用不是问题。错误消息包含使用方法调用计算的图像的完整路径。尽管有完整的路径,React Native还是抱怨缺少带有require的模块。
React 本机版本是0.37.0。我在 ios 模拟器上测试了这个。
不幸的是,这就是react-native打包器的工作原理,require中的图像名称必须是静态的。这是官方的例子docs https://facebook.github.io/react-native/releases/next/docs/images.html:
// 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} />
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)