ReactNativeのImageで画像が表示されなくてはまる
最初に結論
- widthとheightを忘れずに!
Imageタグの使い方
- source属性に画像のURLを設定する
① プロジェクト内に入ってるファイルを使う時
- sourceにファイルをrequire/importしたものを渡す
<Image source={require('./sample.png')} />
② 外部から画像を取得する場合
- uriプロパティにURLを設定したオブジェクトを渡す
<Image source={{ uri: 'https://facebook.github.io/react-native/img/header_logo.png' }} />
ハマりどころ
- ①は特に問題なし
- ②は上記の例だと表示されなくてはまる
解決策
- widthとheightをつけると表示される
- こんな感じ
<Image
source={{ uri: 'https://facebook.github.io/react-native/img/header_logo.png' }}
style={{ width: 66, height: 58 }}
/>
サンプル
import React from 'react';
import { AppRegistry, Image, View } from 'react-native';
const Sample = () => (
<View>
{/* これは問題なく表示される */}
<Image
source={require('./sample.png')}
style={{ backgroundColor: 'lightgreen' }}
/>
{/* これはwidth/heightがないので表示されない */}
<Image
source={{ uri: 'https://facebook.github.io/react-native/img/header_logo.png' }}
style={{ backgroundColor: 'yellow' }}
/>
{/* これはwidth/heightがあるので表示される */}
<Image
source={{ uri: 'https://facebook.github.io/react-native/img/header_logo.png' }}
style={{ width: 66, height: 58, backgroundColor: 'lightblue' }}
/>
</View>
);
AppRegistry.registerComponent('Sample', () => Sample);
- こんな感じ
まとめ
- Imageタグ使う時はwidth/heightを忘れずに