为图像文件反应本机使用变量 [英] react native use variable for image file
问题描述
我知道要在 React Native 中使用静态图像,您需要专门对该图像进行要求,但我正在尝试根据数字加载随机图像.例如,我的目录中有 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.
推荐答案
对于任何了解 react-native 野兽的人,这应该会有所帮助 :)
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.
大漫 - 问:这个答案如何使用变量?
好吧,由于 require
只接受文字字符串,所以不能使用变量、连接字符串等.这是下一个最好的事情.是的,它仍然有很多工作,但现在你可以做一些类似于 OP 的问题的事情:
Well, since require
only accepts a literal string, you can't use variables, concatenated strings, etc. This is the next best thing. Yes, it still is a lot of work, but now you can do something resembling the OP's question:
render() {
var images = { test100: "image100" };
return (
<View>
<Text>
test {images["test" + "100"]}
</Text>
</View>
);
}
这篇关于为图像文件反应本机使用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!