Dynamic loading of locally stored images with react native

隐身守侯 提交于 2021-01-28 06:44:40

问题


Problem with dynamic loading of image resources within a loop/list.

I have all my static local resources required as such:

assets/images.js

const images = {
  appLogo: require('./app-logo.png'),

  cardOne: require('./cards/card-1.png'),
  cardTwo: require('./cards/card-2.png'),
  ...
  cardForty: require(./cards/card-40.png)
}

export default images;

Then in my list screen:

...
import images from '../assets/images';
...
renderListItems(item) {

    const image_name = `images.card${item.cardName}`;
    console.log(image_name); // images.cardOne, images.cardTwo etc..

    return (
        <ListItem avatar>
            <Thumbnail square size={80} source={image_name} /> // This is nativebase component which wraps the RN image component
            <Body>
                <Text>{item.name}</Text>
            </Body>
            <Right>
                <NBIcon name="arrow-forward" />
            </Right>
        </ListItem>
    );
}
...

No resources get loaded. Yet if I change the source={image_name} to source={images.cardOne} directly (where images.cardOne is the exact same as image_name variable on the first iteration) it works - except for the fact that they all have the same image.

I also tried using {{ uri: image_name }} syntax but nothing happens there too.

There doesn't seem to be any solution to this, other than creating a massive switch statement


回答1:


Well that's because image_name is a string with the value of images.cardOne whereas images.cardOne is also a string but with the value of the actual path of the images in your file system (e.g ./app-logo.png). So if you want to load images object dynamically to image_name, you should use the bracket notation like so:

const image_name = images[`card${item.cardName}`];

That way image_name will now point to the path of your images (e.g ./app-logo.png).



来源:https://stackoverflow.com/questions/44610639/dynamic-loading-of-locally-stored-images-with-react-native

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