2016-06-28 3 views
1

このコードは動作します:Xcodeを使わずにダイナミックな文字列で画像を要求することはできますか?

<Image source={require('./../img/icons/mlb/kc.png')} /> 

このコードはしません:

var team = 'kc'; //Retrieved from API 
var string = './../img/icons/mlb/'+team+'.png' 
<Image source={require(string)} /> 

エラー:

Unhandled JS Exception: Requiring unknown module "./../img/icons/mlb/kc.png".If you are sure the module is there, try restarting the packager or running "npm install".

を追加することなく、動的に画像を含めるためにどのような方法がありますそれらをXcodにe?

答えて

2

リアクトウのImage documentationによると、それは不可能である。

Note that in order for this to work, the image name in require has to be known statically.

事前にすべての画像を知っていて、事前に必要としている場合は、これを行うことができます。次に、チーム名をイメージ名として直接使用できます。

このような何か:

var teamA = require("./../img/icons/mlb/teamA.png"); 
var teamB = require("./../img/icons/mlb/teamB.png"); 
var teamC = require("./../img/icons/mlb/teamC.png"); 

// if you like imports better, then: 
// import { default as teamA } from "./img/icons/mlb/teamA.png"; 
// import { default as teamB } from "./img/icons/mlb/teamB.png"; 
// import { default as teamC } from "./img/icons/mlb/teamC.png"; 

const teamByName = (teamName) => { 
    switch (teamName) { 
     case "teamA": return teamA; 
     case "teamB": return teamB; 
     case "teamC": return teamC; 
    } 
}; 

const TeamImage = ({team}) => (
    <Image source={teamByName(team)} /> 
); 

編集:

ところで、あなたはXcodeの経由画像を追加する必要はありません。コンポーネントのように、アプリケーションフォルダの中に配置するだけです。私はこのように私のままにしたい:

ROOT 
| index.ios.js 
| - app 
| |- (other javascript files) 
| - img 
| |- (image files like png, jpg, gif) 
+0

ありがとう、完璧な作品 – jose920405

関連する問題