简体   繁体   English

为什么当我尝试在 react.js 中获取图像的高度和宽度时它返回未定义

[英]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.我正在尝试将图像的高度和宽度值记录到 react.js 中的控制台,但它们(由于某种原因)未定义。 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您可以修改getImgSize方法,如下所示

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 https://codesandbox.io/s/xenodochial-borg-x474m?file=/src/App.js

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当我尝试在我的 react.js 组件中迭代对象数组时,为什么会出现错误? - Why does error appear when I try to iterate array of objects in my react.js component? 新手尝试 react.js 项目。 当我尝试导入图像时,我收到一条无法编译的错误消息 - Newbie trying a react.js project. When I try to import an image I get an error message that it failed to compile 为什么在使用 redux 和 react.js 时我的道具“未定义”? - Why are my props `undefined` when using redux and react.js? React.js-即使我定义了数组也未定义 - React.js - array is undefined even when I defined it 为什么 React.js 中的 1 个 undefined 属性 - Why 1 property of undefined in the React.js 在 React.js 中更改 static SVG 字符串的高度和宽度 - Change height and width of static SVG string in React.js 当我使用babel-preset-es2015和Webpack捆绑jsx文件(react.js)时,为什么“ this”未定义? - Why is 'this' undefined when I bundled the jsx file (react.js) using babel-preset-es2015 and Webpack? 为什么这个 console.logconsole.log(data.lyrics) 在 react.js 中给我 undefined? - why does this console.logconsole.log(data.lyrics) gives me undefined in react.js? JQuery 当我尝试单击元素时,toggleClass 在 React.js 中不起作用 - JQuery toggleClass not working in React.js when i try to click on the element 狗 API 品种返回未定义的 404 错误 React.js - Dog API breeds return undefined 404 error React.js
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM