LoginSignup
1

More than 1 year has passed since last update.

[React Native]幅によって画像の高さを動的に変更する方法

Posted at

はじめに

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によって管理するため、画像の数が不定の場合はコンポーネントにする必要があります。表示する画像数が決まっていて、コンポーネントを再利用する必要のない場合は、コンポーネントにしなくても問題ないかと思います。

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
1