You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native FlatList本地图片无法显示,报invalid call错误求助

解决Expo React Native FlatList加载本地图片的"invalid call"错误

问题原因

React Native的require()不支持动态传入路径变量。Metro打包工具需要在构建阶段提前定位所有本地资源,动态路径(比如require(item.id))无法被预解析,因此触发"invalid call"错误。

修复步骤

1. 预加载本地图片资源

修改EXAMPLES数组,直接将图片的require()结果存入数组,同时给每个项设置独立的唯一ID(避免用路径作为key,稳定性更好):

const EXAMPLES = [
    {
        id: 'img-1',
        image: require('../assets/img-1.png'),
        prompt: 'A synthwave style sunset above the reflecting water of the sea, digital art'
    },
    {
        id: 'img-2',
        image: require('../assets/img-2.png'),
        prompt: 'A van Gogh style painting of an American football player'
    },
    {
        id: 'img-3',
        image: require('../assets/img-3.png'),
        prompt: '3D render of a cute tropical fish in an aquarium on a dark blue background, digital art'
    },
    {
        id: 'img-4',
        image: require('../assets/img-4.png'),
        prompt: 'A cartoon of a cat catching a mouse'
    },
    {
        id: 'img-5',
        image: require('../assets/img-5.png'),
        prompt: 'A comic book cover of a superhero wearing headphones'
    },
    {
        id: 'img-6',
        image: require('../assets/img-6.png'),
        prompt: 'A hand-drawn sailboat circled by birds on the sea at sunrise'
    },
    {
        id: 'img-7',
        image: require('../assets/img-7.png'),
        prompt: 'An expressive oil painting of a basketball player dunking, depicted as an explosion of a nebula'
    },
    {
        id: 'img-8',
        image: require('../assets/img-8.png'),
        prompt: 'A hand drawn sketch of a Porsche 911'
    },
    {
        id: 'img-9',
        image: require('../assets/img-9.png'),
        prompt: 'A sea otter with a pearl earring" by Johannes Vermeer'
    },
];

2. 调整FlatList的renderItem逻辑

将Image组件的source改为直接引用数组中预加载的图片资源:

renderItem={({ item }) => (
    <Image
        source={item.image}
        onPress={() => handleSelectedImage(item)}
        transition={true}
        containerStyle={styles.item}
        PlaceholderContent={<ActivityIndicator />}
    />
)}

额外注意

  • 确认图片路径与当前组件文件的相对位置正确,避免路径错误导致资源无法找到
  • keyExtractor依然可以使用item.id,现在的id是独立唯一标识,比路径更适合作为列表项的key

内容的提问来源于stack exchange,提问作者johnDoe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 04:05:19