首頁 >web前端 >js教程 >為什麼我的 React 應用程式中未載入本機圖像?

為什麼我的 React 應用程式中未載入本機圖像?

Linda Hamilton
Linda Hamilton原創
2024-11-15 13:58:03203瀏覽

Why are Local Images Not Loading in My React App?

Local Images Not Loading in React App

In React, it's common to encounter issues where local images fail to load while external images do. This problem can arise when using Webpack, a bundler that optimizes and packages front-end code.

Understanding the Issue

Webpack includes assets, such as images, into the bundled code. By default, it does not recognize local images without explicit inclusion. This is because Webpack expects images to be imported as modules, allowing it to process and optimize them.

Solution: Requiring Local Images

To resolve the issue, you need to require local images in your React components. Replace the following:

<img src={"/images/resto.png"} />

With:

<img src={require('/images/resto.png')} />

By requiring images, you explicitly include them in the Webpack bundle, allowing it to process and replace the source path with the correct bundle asset. This way, React can successfully load local images from the compiled code.

By making this modification, you should be able to load local images in your React application without any issues.

以上是為什麼我的 React 應用程式中未載入本機圖像?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn