【问题标题】:TypeScript React <img /> onLoad event.target can't find naturalWidth naturalHeightTypeScript React <img /> onLoad event.target 找不到 naturalWidth naturalHeight
【发布时间】:2019-10-19 16:11:42
【问题描述】:

return <img {...props} onLoad={event => {
  console.log(event.target.naturalWidth)
}}/>

我想在 TypeScript React 中检索 naturalWidth 和 naturalHeight。

但是卡住了,TypeScript 找不到那个属性。

如何在 TypeScript React 中检索 naturalWidth 和 naturalHeight?

【问题讨论】:

  • 你可以使用 let image = event.target 作为 HTMLImageElement; console.log(event.target.naturalWidth);在 onload 函数体内。
  • @Ganeshchaitanya 谢谢,我认为这是唯一的方法。

标签: html reactjs image typescript


【解决方案1】:

您可以通过event.currentTarget(而不是event.target)访问HTMLImageElement,所以这应该可以工作:

return <img {...props} onLoad={event => {
  console.log(event.currentTarget.naturalWidth)
}}/>

【讨论】:

    【解决方案2】:

    你可以试试innerWidth和innerHeight。

    console.log(event.target.innerWidth)

    【讨论】:

    • 但我想要原始宽度和高度
    • $(document).ready(function(){ $("button").click(function(){ var img = $("#sky"); // 创建虚拟图像来获取实际大小 $("").attr("src", $(img).attr("src")).load(function(){ var realWidth = this.width; var realHeight = this.height; alert("原始宽度=" + realWidth + ", " + "原始高度=" + realHeight); }); }); });试试这个。
    • 那是 jQuery,我想要 TypeScript React 解决方案。
    猜你喜欢
    • 2016-02-20
    • 1970-01-01
    • 1970-01-01
    • 2022-09-27
    • 1970-01-01
    • 2018-05-28
    • 2021-07-13
    • 2019-12-29
    • 2018-10-15
    相关资源
    最近更新 更多