0

我在文件夹 assets/dummy-data/Avatars.ts 中创建了一个名为 avatars 的虚拟数据文件。

export default [
    {id: 1, levels: ["pichu", "picachu", "raichu"]},
    {id: 2, levels: ["charmander", "charmeleon", "charizard"]},
    {id: 3, levels: ["totodile", "croconaw", "feraligatr"]},
    {id: 4, levels: ["squirtle", "wartortle", "blastoise"]},
    {id: 5, levels: ["bulbasaur", "ivysaur", "venusaur"]},
    {id: 6, levels: ["cyndaquil", "quilava", "typhlosion"]},
    {id: 7, levels: ["pidgey", "pidgeotto", "pidgeot"]},
    {id: 8, levels: ["turtwig", "grotle", "torterra"]},
    {id: 9, levels: ["igglybuff", "jigglypuff", "wigglytuff"]},
    {id: 10, levels: ["cleffa", "iclefairy", "clefable"]},
    {id: 11, levels: ["litten", "torracat", "incineroar"]},
    {id: 12, levels: ["nidoran", "nidorina", "vnidoqueen"]},
]

我想要做的是将这些数据加载到另一个文件中,然后用它们制作一个 Flatlist 组件。我的代码是:

import { StyleSheet, Text, View, FlatList, Image } from 'react-native'
import Avatars from '../assets/dummy-data/Avatars'

const OnboardingScreen = () => {
    const test = "charizard"
    console.log(Avatars)
    return (
        <View>
            <FlatList
                data = {Avatars}
                renderItem = {
                    ({item}) =>
                        (
                            <Image source={require(`../assets/images/avatars/${{item}.levels[0]}pichu.jpg`)} />
                        )
                }
            />
        </View>
    )
}

export default OnboardingScreen

const styles = StyleSheet.create({})

这是我得到的错误: 错误的屏幕截图

谢谢

4

1 回答 1

0

React Native 不支持动态图像。目前,仅支持静态图像资源,因为 require 中的图像名称必须是静态已知的。

// 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} />

为了解决您的问题,更改您的头像数据如下

export default [
    {
        id: 1, levels: [
            require('./assets/images/avatars/pichu.jpg'),
            require('./assets/images/avatars/picachu.jpg'),
            require('./assets/images/avatars/raichu.jpg')
        ]
    },
    {
        id: 2, levels: [
            require('./assets/images/avatars/charmander.jpg'),
            require('./assets/images/avatars/charmeleon.jpg'),
            require('./assets/images/avatars/charizard.jpg')
        ]
    },
]

然后你可以渲染你的图像

<Image source={item.levels[0]} />

希望这对您有所帮助。随意怀疑。

于 2021-11-06T05:32:54.913 回答