Maison >interface Web >js tutoriel >Pourquoi les images locales ne se chargent-elles pas dans mon application React ?

Pourquoi les images locales ne se chargent-elles pas dans mon application React ?

Linda Hamilton
Linda Hamiltonoriginal
2024-11-15 13:58:03202parcourir

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.

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn