2016-10-12 95 views
3

我有大約100個需要導入到listview的本地英雄圖像。這是我的hero.jsReact Native:如何用動態名稱導入本地圖像

renderRow(hero) { 
return (
      <View> 
       <View style={styles.container}> 
        <Image 
         source={require('./img/hero/'+hero.img+'.jpg')} 
         style={styles.thumbnail} /> 
        <View style={styles.rightContainer}> 
         <Text style={styles.title}>{hero.name}</Text> 
        </View> 
       </View> 
       <View style={styles.separator} /> 
      </View> 
); 

一些研究,我知道後需要不會允許動態域名。我也試過uri,沒有錯誤,但沒有圖像。

{{uri: './img/hero/'+hero.img+'.jpg'}} 

我的文件夾結構是這樣的:

Project 
    index.ios.js 
    hero.js 
    img 
    hero 

什麼是處理這個問題的最好方式,我不希望把圖像在網絡上。

回答

0

sahrens下面說這個forum

我們故意,因爲這使得它很難隨着時間的推移管理資產不支持動態生成圖像的名字,就像你怎麼會不想做

它看起來可以通過uri完成,但它需要一點工作。您將需要在xcode資源中添加圖像,並在res/drawable下爲android添加圖像。

然後你就可以用<Image source={{ uri: "image" + "name" }} />

+2

我看到了,但是手動將所有圖像添加到xcode assets資源文件夾中並不好玩:( –

0

我以某種方式解決了這個問題,讓你的形象,只是在這裏發佈我的回答的情況下,其他人如何處理這個有趣的。

我寫了一個PHP腳本讀取所有的圖像在我心目中的英雄的文件夾,並在此格式打印出來:

heroName: require ('./img/hero/heroName.jpg')

<?php 
    $dir = "./img/hero"; 

    // Open a known directory, and proceed to read its contents 
    if (is_dir($dir)) { 
     if ($dh = opendir($dir)) { 
      $images = array(); 

      while (($file = readdir($dh)) !== false) { 
       $keyName = str_replace(".jpg","",$file); 
       print "$keyName: require('./img/hero/$file'),". "<br />"; 
      } 

      closedir($dh); 

     } 
    } 
?> 

然後我複製的結果,粘貼到一個js文件,並存儲對象是這樣的:

export default heroList = { 
    name1: require('./img/hero/name1.jpg'), 
    name2: require('./img/hero/name2.jpg'), 
    etc.... 
} 
我hero.js文件

最後

相關問題