react-native - React Native - 提供给`Image`的无效道具`source` - 连接图像源字符串
问题描述
当我连接源字符串时,我有来自道具的图像源:require(../assets/images/${props.image})
. 然后我在图像的源属性上调用它,我得到一个错误:失败的道具类型:无效的道具source
提供给Image
.
有没有人可以帮忙,非常感谢<3
function Category(props) {
let image = `require(../assets/images/${props.image})`;
console.log(image);
return (
<TouchableOpacity style={styles.container}>
<View>
<Image style={{ width: 60, height: 60 }} source={image}></Image>
<Image style={{ height: 10, width: 12 }} source={require('../assets/images/Layer1.png')}></Image>
</View>
<View></View>
</TouchableOpacity>
);
}
Category 由 FlatList 上的 renderItem 调用,item.image 为 image 的文件名:layer1.png, layer2.png... 父组件-MainScreen:
function MainScreen({ navigation }) {
return (
<Screen style={styles.container}>
<Header isHome={true}>HOME</Header>
<ScrollView>
<View style={styles.main}>
<Carousel data={bannerSlide} />
<Text>Go to Detail</Text>
<View style={styles.category}>
<FlatList
style={styles.dishList}
data={dishList}
keyExtractor={item => item.label.toString()}
horizontal
snapToAlignment="center"
scrollEventThrottle={16}
showsHorizontalScrollIndicator={false}
renderItem={({ item }) =>
<Category
name={item.name}
image={item.image}
/>
}
/>
</View>
</View>
</ScrollView>
</Screen>
);
}
解决方案
您正在尝试将字符串传递给image
变量,并且源将失败,因为您正在提供字符串。您需要像下面这样更新它
let image = require(`../assets/images/${props.image}`);
require
在设备上呈现应用程序之前嵌入所有图像,这意味着您不能在 require 中使用动态本地路径。你可以在这里阅读更多信息。您最好的方法是将资源嵌入到单独的 js 文件中并从那里导出它们,然后在需要它们的任何地方导入和引用它们。
例如,有一个带有以下代码的 imageManager.js
export default {
first_image: require('./image.png');
}
然后在您的组件中,您可以像下面这样使用它们
import images from './imageManager';
function Category(props) {
let image = images[props.image];
...
props.image 然后可以设置为 'first_image' 等等。
希望这有帮助。
推荐阅读
- google-cloud-platform - 创建新实例时如何防止谷歌计算创建新用户
- python - 修改 python 列表的一部分时会发生什么
- prestashop - 在 ps 语言切换器 prestashop 1.7 中显示 3 个字母
- angular - 在 FullCalendar Angular 中的每一天添加图标
- c++ - C++ - 如何将 char* 子字符串解析为 int?
- azure - Azure - Copy file to FTP every 10 minutes
- google-chrome - What's the difference of Step and Step Into in Google Chrome developer tools?
- r - Is there a R function which can undo cumsum() and recreate the original non-cumulative column in a dataset?
- c# - 带有组合框的 ICollectionView
- c# - 使用 Microsoft.Azure.Management.ApiManagement 以编程方式将 API 导入 Azure API 管理 (APIM)