[英]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.