簡體   English   中英

從 onLoad() 返回的 React 合成事件<image>里面的元素<svg>沒有 naturalWidth 或 naturalHeight 屬性

[英]React synthetic event returned from onLoad() of <image> element inside <svg> does not have naturalWidth or naturalHeight properties

我正在使用 ReactJS。 我的目標是在 SVG 元素內加載圖像時觸發一些事件。

如果沒有 SVG 元素,下面的代碼將按預期工作-

function onImageLoad(event) {
   console.log("Event triggered from <img> element", event);
    // AS EXPECTED : Event object has natural width and natural height
  }

return (
      <div>
        <img src={imageName} onLoad={ (event) => onImageLoad(event) }/> 
      </div>
)

但是,此代碼無法按預期工作-

function onImageLoad(event) {
    console.log("Event triggered from <image> element", event);
    // UNEXPECTED : Event object does not have natural width or natural height
  }

return (
      <div>
        <svg>
          <image href={imageName} onLoad={ (event) => onImageLoad(event) }/> 
        </svg>
      </div>
)

我曾嘗試在幾個地方閱讀。 不清楚為什么<image><img>onLoad()合成事件在反應中不同。

HTMLImageElement不同, SVGImageElement接口不公開naturalWidthnaturalHeight屬性,也沒有任何方法來檢索內部圖像的固有大小。

如果你想得到它,最簡單的方法是在 HTML <img>中再次加載圖像,另一種方法是從<image>創建ImageBitmap ,但並非所有瀏覽器都支持它。

 const svgImg = document.querySelector("image"); const getSVGImageSize = async (src) => { const img = new Image(); img.src = src.href.baseVal; await img.decode(); const { width, height } = img; return { width, height }; }; getSVGImageSize(svgImg) .then(({ width, height }) => console.log("from HTMLImageElement", { width, height })) // alternative using createImageBitmap, // not supported in Safari svgImg.addEventListener("load", e => createImageBitmap(svgImg) .then(({ width, height }) => console.log("fom ImageBitmap", { width, height })) .catch(console.error) );
 <svg> <image href="https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png"/> </svg>

您需要傳遞 event.currentTarget,而不是事件本身

<image href={imageName} onLoad={ (event) => onImageLoad(event.currentTarget) }/> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM