我知道要在 React Native 中使用静态图像,您需要专门对该图像执行要求,但我正在尝试根据数字加载随机图像。例如,我的目录中有 100 张名为 img1.png - img100.png 的图像。我正在尝试找出一种方法来执行以下操作
<Image source={require(`./img${Math.floor(Math.random() * 100)}.png`)}/>
我知道这不是故意的,但如果有任何变通办法,我们将不胜感激。
最佳答案
对于任何了解 react-native 野兽的人来说,这应该有所帮助:)
我过去也访问过几个网站,但发现它越来越令人沮丧。直到我读到 this site here .
这是一种不同的方法,但它最终会带来返回。 基本上,最好的方法是将所有资源加载到一个地方。 考虑以下结构
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;
在您的 View 中,您必须像这样导入图像组件:
import Images from './img/index';
render() {
<Image source={Images.profile.comments} />
}
每个人都有不同的手段,选择最适合自己的。
大满-问:这个答案怎么用变量?
好吧,因为 require
只接受文字字符串,所以你不能使用变量、连接字符串等。这是次要的事情。是的,这仍然是很多工作,但现在你可以做一些类似于 OP 问题的事情:
render() {
var images = { test100: "image100" };
return (
<View>
<Text>
test {images["test" + "100"]}
</Text>
</View>
);
}
关于javascript - 对图像文件 react native 使用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33907218/