简体   繁体   中英

Why does it return undefined when I try to get the height and width of an image in react.js

I'm trying to log the height and the width values of an image to the console in react.js but they are (for some reason) undefined. Do you know why it is?

Here's the code:

export default function FilmPage(props) {
    const getImgSize = (img) => {
        let imageEl = <img onLoad={()=>{
            console.log(imageEl.width)
            console.log(imageEl.height)
        }} src={img} />

        return imageEl
    }
    
    return (
        <div className="proper-film">
            <div className="body">
                <div>{getImgSize(props.data.image)}</div>
            </div>
        </div>
    )

}

And also the data I retrieve looks like this:

data = {
    some: null,
    other: null,
    stuff: null,  
    image: "https://my_api.com/images/original/picture.jpg",
    and_more: null
}

By the way, when I tried debugging, there was no problem with the data I retrieve.

What would you recommend?

You can modify getImgSize method like below

const getImgSize = (img) => {
    return <img onLoad={(e) => {
      console.log(e.target.offsetHeight)
      console.log(e.target.offsetWidth)
    }} src={img} />


  }

https://codesandbox.io/s/xenodochial-borg-x474m?file=/src/App.js

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM