LoginSignup
2
1

More than 3 years have passed since last update.

【ReactNative】内部画像ファイルを動的に読み込む

Posted at

環境

  • React Native 0.63

問題

外部ネットワークからと同じ要領で Image コンポーネントの source に、パスを格納した変数を渡し、画像を読み込もうとするとエラーになる。

<Image source={require(pathToImageFile)} />

解決方法

予め静的ファイル群を読み込んだオブジェクトを参照する。
なお、オブジェクトは階層化しない方が変数での読み込みが簡単にしやすい。

assets/images/index.ts
import { ImageSourcePropType } from 'react-native';

export enum imageNames {
  noImage = 'noImage',
  defaultProfileImage = 'defaultProfileImage',
}

export const images: { [key in imageNames]: ImageSourcePropType } = {
  noImage: require('./noImage.jpg'),
  defaultProfileImage: require('./defaultProfileImage.png'),
};

動的に呼び出したいファイル.tsx
import { imageNames } from '@src/assets/images';

const Component: React.FC = () => (
  <Image source={imageNames.defaultProfileImage} />
);

参考記事

編集後記

ReactNativeでは画像は外部ソースから読み込むことが多いし、内部に置いている画像はロゴなど数少ないので、動的に読み込む機会が少ない。
思いのほか躓いた部分だった。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1