首页 > 解决方案 > 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>
);
}

标签: react-native

解决方案


您正在尝试将字符串传递给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' 等等。

希望这有帮助。


推荐阅读