简体   繁体   English

从包含许多文件的文件夹中反应本机动态导入图像

[英]react native dynamic import image from folder containing many files

I have a image folder say answers where I am storing answer for my question which are images我有一个图像文件夹,上面写着answers ,我在其中存储了我的问题的答案,这些答案是图像

There are 200 images for now in that folder.该文件夹中目前有 200 张图像。

Now I want to show the image of the answer according to the user's answer.现在我想根据用户的答案显示答案的图像。

I am generating the answers randomly我随机生成答案

`var answer = getAnswers(data)` // some calculation for file name for answer

<Image source={require('../path/to/my/answer/' + answer + '.jpg')}

Doing this I am getting error ``require expect exactly 1 string literal argument这样做我收到错误``需要expect exactly 1 string literal argument

I came to know that builder needs to know the location before building.我开始知道建造者需要在建造之前知道位置。 But how to solve this type of issue.但是如何解决此类问题。

I can not map 200 files initailly for require我无法为 require initailly 映射 200 个文件

var one = require('../path/one.jpg')
var two = require('../path/two.jpg')

How can I solve this type of issue.我该如何解决此类问题。 Is there any way to do this ??有没有办法做到这一点?

Help needed.需要帮助。

A dynamic search path in require is simply not possible. require 中的动态搜索路径根本不可能。

From what I understand you have 2 options here:据我了解,您在这里有两个选择:

1. Generate an Image file 1.生成Image文件

Instead of writing 200 lines by hand you can make a script that scans through your image folder and generates a list of image urls.您可以编写一个脚本来扫描图像文件夹并生成图像 url 列表,而不是手动编写 200 行。 I would suggest a format similar to:我建议采用类似于以下格式的格式:

// Images.js

export const Answers = { 
   ANSWER_ONE : require('../path/one.jpg'),
   ANSWER_TWO : require('../path/two.jpg'),
   ...
}

Then use it:然后使用它:

import {Answers} from './Images'

var answer = getAnswers(data)

<Image source={Answers[answer]} />

2. Copy image files to asset folders 2. 将图片文件复制到资产文件夹

If choosing this option you have to copy all image files to both your android and ios projects assets folder.如果选择此选项,您必须将所有图像文件复制到您的 android 和 ios 项目资产文件夹。 You are then able to use them like this:然后,您可以像这样使用它们:

var answer = getAnswers(data)

<Image source={{uri: '../path/to/my/answer/' + answer + '}} />

Read more about using image assets . 阅读有关使用图像资产的更多信息

... ...

Even though the second option seems tempting I would prefer the first in most cases.尽管第二个选项看起来很诱人,但在大多数情况下我更喜欢第一个。 Mostly because the second requires you to make two copies every time you add an image (assuming you supporting both android and ios).主要是因为第二个要求您每次添加图像时制作两个副本(假设您同时支持 android 和 ios)。 Also, option 1 gives your better typing suggestions where you won't misspell the image name.此外,选项 1 提供了更好的键入建议,您不会拼错图像名称。

Hope this helps!希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM