Setting source of <Image/> with variable

谁都会走 提交于 2021-01-28 08:53:05

问题


I am trying some react native code which is as follows , I want to set the static images to an image view as follows but it doesn't load

const items = [
            { name: './images/home.png', code: '#1abc9c' }, { name: './images/home.png', code: '#2ecc71' },
            { name: './images/home.png', code: '#3498db' }, { name: './images/home.png', code: '#9b59b6' }
        ];

        return (
            <ImageBackground
                source={require('./images/marble.jpg')}
                style={styles.backgroundImage}>

                <GridView
                    itemDimension={130}
                    items={items}
                    style={styles.gridView}
                    renderItem={item => (
                        <View style={[styles.itemContainer, { backgroundColor: item.code }]}>
                            <Image source={require(item.name)}></Image>
                        </View>
                    )}
                />

            </ImageBackground>
        );

Error I get is

calls to require expect exactly 1 string literal argument, but this was found: require(item.name).

Ofcourse I am new to react native so kindly ignore my missed terminology


回答1:


You try like this

const items = [{ name: require('./images/home.png'), code: '#1abc9c' },{...}]

then

<Image source={item.name}></Image>


来源:https://stackoverflow.com/questions/49138290/setting-source-of-image-with-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!