Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
182 views
in Technique[技术] by (71.8m points)

reactjs - Not showing images in browser - React

I am trying to fetch the right image based on current state in my function, but for some reason everything works, just images are not available in browser and I have no idea why.

 const [firstImage, setFirstImage] = useState(1); //name of the image is 1.png

Returning an image - the path is of course correct:

<img src={`../assets/images/${firstImage}.png`}/>
question from:https://stackoverflow.com/questions/65939247/not-showing-images-in-browser-react

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First you need to import your images, then add the images your state or an array of images. Then you can target or cycle through the images with your setImage index state value.

These links show why you cant just use pathnames:

https://create-react-app.dev/docs/adding-images-fonts-and-files/

https://www.edwardbeazer.com/importing-images-with-react/

https://daveceddia.com/react-image-tag/

Heres an example: https://codesandbox.io/s/competent-rgb-zxz36?file=/src/App.js:0-346

import React, { useState } from "react";
import "./styles.css";
// import img1 from "./img/img1.jpg"; // you can import them
// import img2 from "./img/img2.jpg";

export default function App() {
  const img1 = require(`./img/img1.jpg`); // or you can require them
  const img2 = require(`./img/img2.jpg`);
  const images = [img1, img2];
  const [currentImage, setCurrentImage] = useState(0);
  return (
    <div className="App">
      <img src={images[currentImage]} />
    </div>
  );
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...