将本机使用变量用于图像文件 [英] react native use variable for image file

查看:111
本文介绍了将本机使用变量用于图像文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道要在本机中使用静态图像,您需要专门对该图像执行要求,但我尝试根据数字加载随机图像。例如,我在我的目录中有100个名为img1.png - img100.png的图像。我试图找出一种方法来执行以下操作

I know that to use a static image in react native you need to do a require to that image specifically, but I am trying to load a random image based on a number. For example I have 100 images called img1.png - img100.png in my directory. I am trying to figure out a way to do the following

<Image source={require(`./img${Math.floor(Math.random() * 100)}.png`)}/>

我知道这有意无效,但任何变通办法都会非常感激。

I know this intentionally does not work, but any workarounds would be greatly appreciated.

推荐答案

对于任何了解反应原生兽的人来说,这应该有所帮助:)

For anyone getting to know the react-native beast, this should help :)

我过去也访问了几个网站,但发现它越来越令人沮丧。直到我读到这个网站在这里

I visited a couple of sites in the past too, but found it increasingly frustrating. Until I read this site here.

这是一种不同的方法,但它最终会得到回报。
基本上,最好的方法是将所有资源加载到一个地方。
考虑以下结构

It's a different approach but it eventually does pay off in the end. Basically, the best approach would be to load all your resources in one place. Consider the following structure

app  
   |--img
      |--image1.jpg
      |--image2.jpg
      |--profile
          |--profile.png
          |--comments.png
      |--index.js

index.js 中,你可以这样做:

const images = {
    profile: {
        profile: require('./profile/profile.png'),
        comments: require('./profile/comments.png'),
    },
    image1: require('./image1.jpg'),
    image2: require('./image2.jpg'),
};

export default images;

在您的视图中,您必须导入图像组件,如下所示:

In your views, you have to import the images component like this:

import Images from './img/index';

render() {
    <Image source={Images.profile.comments} />
}

每个人都有不同的手段来结束,只需选择最适合你的方式。

Everybody has different means to an end, just pick the one that suits you best.

这篇关于将本机使用变量用于图像文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆