javascript - 在本机反应中,图像未从状态显示
问题描述
我已经在状态中保存了图像名称,但是当我尝试显示它们时,它给出了错误“无效调用需要('./assets/'+this.state.img1)”(但是当我将图像名称直接放在源中时它的开头工作。喜欢:我也提醒该州它具有相同的图像名称。
render() {
return (
<TouchableOpacity onPress={this.onItemPressed} style={styles.container}>
<Image
style={styles.stretch}
source={require('./assets/'+this.state.img1)}
/>
<Image
style={styles.stretch}
source={require('./assets/'+this.state.img2)}
/>
</TouchableOpacity>
)
}
解决方案
根据文档:In order for this to work, the image name in require has to be known statically.
// 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} />;
您可以做的是构建映射/对象:
const myImages = {
img1: require('/path/to/img1'),
img2: require('/path/to/img2'),
};
render() {
return (
<TouchableOpacity onPress={this.onItemPressed} style={styles.container}>
<Image
style={styles.stretch}
source={myImages[this.state.img1]}
/>
<Image
style={styles.stretch}
source={myImages[this.state.img2]}
/>
</TouchableOpacity>
)
}
为此,this.state.img1
它this.state.img2
必须是 object 中的一个键myImages
。
推荐阅读
- azure - Azure 存储帐户队列获取新消息到达(理想的逻辑应用程序)
- python - Django 将 values 或 values_list 与不相关的模型一起使用
- python - 如何在 Django 模板中使用 instaceof?
- sharepoint - Sharepoint 在“AllItems.aspx”中显示(不完整)ID
- mysql - 是否有一个 SQL 函数仅在基于另一个条件未找到行值时才返回行
- asp.net-mvc - 如何将整个 ASP.NET MVC 网站从 www.test.com 移动到 www.test.com/xyz
- javascript - 围绕潜在获取错误进行编码的常规方法?
- python - 如何在 Pandas 中遍历 DataFrame 中的行和索引以过滤布尔值
- java - 在树莓派上使用 Jython 的 Spring Boot 应用程序
- node.js - Ubuntu 中的 npx create-react-app 错误