はじめに
React Nativeでブログやコラムなどを実装する場合、実装の段階でどの高さの画像が表示されるかがわからないことがあります。そのような時に、画像によってstyleのheight
プロパティを動的に変更する方法をご紹介します。
バージョン
"dependencies": {
"react-native": "0.63.4",
}
実装内容
import React, { useEffect, useState } from 'react'
import { Image, View, Dimensions, StyleSheet } from 'react-native'
interface Props {
url: string
}
export const CoverImage = ({ url }: Props) => {
const [imageWidth, setImageWidth] = useState(Dimensions.get('window').width)
const [imageHeight, setImageHeight] = useState(200)
useEffect(() => {
Image.getSize(url, (width, height) => {
if (width && height) {
setImageHeight((height * imageWidth) / width)
}
})
}, [])
return (
<Image
source={{ url: url }}
resizeMode="cover"
style={{width: imageWidth, height: imageHeight}}></Image>
)
}
実装の通り、画像の幅、高さをstateによって管理するため、画像の数が不定の場合はコンポーネントにする必要があります。表示する画像数が決まっていて、コンポーネントを再利用する必要のない場合は、コンポーネントにしなくても問題ないかと思います。