はじめに
こんにちは、梅雨です。
今回は、ReactNative においてリモートの画像を簡単に表示できるようにするカスタムコンポーネントの設計を紹介します。
カスタムコンポーネント
結論から話すと、以下のようなカスタムコンポーネントを作成しました。
import { useState } from "react";
import { Image, ImageStyle, StyleProp } from "react-native";
const RemoteImage = ({ src, style }: { src: string; style?: StyleProp<ImageStyle> }) => {
const [aspectRatio, setAspectRatio] = useState(1);
return (
<Image
source={{ uri: src }}
style={[
{ aspectRatio, marginHorizontal: "auto" },
aspectRatio > 1 ? { width: "100%" } : { height: "100%" },
style
]}
onLoad={(e) => {
const { width, height } = e.nativeEvent.source;
setAspectRatio(width / height);
}}
/>
);
};
export default RemoteImage;
ポイントとしては、
-
aspectRatio
をステートとして保持 - 画像ロード時にアスペクト比を計算してステートにセット
- Props でスタイルを受け取り上書き可能
のようになっています。
使用例
実際の使い方は以下のようになります。
src
には画像の URL を、style
には通常のコンポーネントのようにスタイルを記述することができます。
<RemoteImage src="https://picsum.photos/600/400" style={{ borderRadius: 10 }} />