HTML 元素觸發的 load 事件預設不會冒泡到 window 物件。因此,當使用 img HTML 元素載入圖像時,如果需要通知 window 對象,則必須手動向其調度事件。
範例:
HTML
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <img> <p>JS<br> </p> <pre class="brush:php;toolbar:false">document.getElementById('image').addEventListener('load', function() { console.log('Image load event'); window.dispatchEvent(new Event('load')); // Manually dispatch load event to window }); window.addEventListener('load', function() { console.log('Window load event'); });
控制台輸出:第二個日誌「Window Load Event」是透過呼叫dispatchEvent
觸發的
Image load event Window load event Window load event
模擬 API 呼叫來取得影像 URL 並將其傳遞給 Banner 元件,當 imgUrl 變更時會觸發重新渲染,從而允許在第二個渲染階段擷取正確的 Completed 值。
import { useRef , useState , useEffect } from "react"; export default function App() { const [imgUrl, setImgUrl] = useState(""); useEffect(() => { // simulate calling API to get image url const loadImage = () => { setTimeout(() => { setImgUrl("https://placehold.co/200x100") }, 1500); } loadImage(); }, []); return <Banner imgUrl={imgUrl} /> } function Banner({ imgUrl }) { const ref = useRef(null); // this works when the imgUrl changes, triggering a re-render. Otherwise, the value of completed will always be false const completed = Boolean(ref.current?.complete); return ( <div> <img ref={ref} src={imgUrl} onLoad={() => console.log("loaded")} onError={() => console.log("error")}/> <p>{completed ? "Image loaded" : "Image is not loaded"}</p> </div> ); }
在onLoad事件回呼中更新元件狀態
function StaticBanner() { const [loaded, setLloaded] = useState(false); return ( <div> <img src="https://placehold.co/100x100" onLoad={() => { console.log("StaticBanner img loaded"); setLloaded(true); }} onError={() => console.log("StaticBanner img error")}/> <p>{loaded ? "Image loaded" : "Image is not loaded"}</p> </div> ); }
未完待續...
以上是如何在 React 中載入映像後執行操作:使用 onLoad 事件或complete 屬性的詳細內容。更多資訊請關注PHP中文網其他相關文章!