How to dynamically adjust the size of the img tag in react to ensure that the displayed picture does not exceed the specified length and width

problem description

cannot find a method to dynamically obtain the width and height of the original picture

the environmental background of the problems and what methods you have tried

if the original picture is small, img will follow the size of the original picture, and if the picture is too large, the img will be reduced to the specified width and height
it won"t work in the way of ordinary html

.
Sep.09,2021

you can use the object-fit attribute, which should meet your needs

can maintain the original size ratio. Make sure that the size of the replacement content must be larger than the container size, and that at least one of the width and height is the same as the container.

img{
    width:50px;
    height:50px;
    object-fit:cover;
}

clipboard.png


naturalWidth and naturalHeight you can get the original size of the picture element

Menu